using System;
using System.Collections.Generic;
using System.Text;
class Program
{
// Remove last n occurrences of a substring
static string RemoveLastN(string s, string sub, int n) {
List<int> positions = new List<int>();
int pos = s.IndexOf(sub);
// Find all occurrences
while (pos != -1) {
positions.Add(pos);
pos = s.IndexOf(sub, pos + sub.Length);
}
// Remove from the end
StringBuilder sb = new StringBuilder(s);
for (int i = positions.Count - 1; i >= 0 && n > 0; i--, n--) {
int start = positions[i];
sb.Remove(start, sub.Length);
}
return sb.ToString();
}
// Remove extra spaces (collapse multiple spaces, trim ends)
static string RemoveExtraSpaces(string s) {
string[] parts = s.Trim().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
return string.Join(" ", parts);
}
static void Main()
{
string text = "abc xyz xyz abc xyzabcxyz abc";
string result = RemoveLastN(text, "xyz", 3);
Console.WriteLine(result);
string cleaned = RemoveExtraSpaces(result);
Console.WriteLine(cleaned);
}
}
/*
run:
abc xyz abc abc abc
abc xyz abc abc abc
*/