How to remove the last n occurrences of a substring in a string in C#

1 Answer

0 votes
using System;
using System.Collections.Generic;
using System.Text;

class Program
{
    // Remove last n occurrences of a substring
    static string RemoveLastNOccurrences(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 = RemoveLastNOccurrences(text, "xyz", 3);
        Console.WriteLine(result);

        string cleaned = RemoveExtraSpaces(result);
        Console.WriteLine(cleaned);
    }
}



/*
run:

abc xyz  abc abc abc
abc xyz abc abc abc

*/

 



answered Feb 15 by avibootz
edited Feb 16 by avibootz

Related questions

...