Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,950 questions

51,892 answers

573 users

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 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

*/

 



answered 2 hours ago by avibootz
...