How to remove the last n occurrences of a substring in a string in VB.NET

1 Answer

0 votes
Imports System
Imports System.Text
Imports System.Collections.Generic

Module Module1

    ' Remove last n occurrences of a substring
    Function RemoveLastNOccurrences(s As String, subStr As String, n As Integer) As String
        Dim positions As New List(Of Integer)()
        Dim pos As Integer = s.IndexOf(subStr)

        ' Find all occurrences
        While pos <> -1
            positions.Add(pos)
            pos = s.IndexOf(subStr, pos + subStr.Length)
        End While

        Dim sb As New StringBuilder(s)

        ' Remove from the end
        For i As Integer = positions.Count - 1 To 0 Step -1
            If n = 0 Then Exit For
            sb.Remove(positions(i), subStr.Length)
            n -= 1
        Next

        Return sb.ToString()
    End Function

    ' Remove extra spaces (collapse multiple spaces, trim ends)
    Function RemoveExtraSpaces(s As String) As String
        Dim parts = s.Trim().Split(New Char() {" "c}, StringSplitOptions.RemoveEmptyEntries)
        Return String.Join(" ", parts)
    End Function

    Sub Main()
        Dim text As String = "abc xyz xyz abc xyzabcxyz abc"

        Dim result As String = RemoveLastNOccurrences(text, "xyz", 3)
        Console.WriteLine(result)

        Dim cleaned As String = RemoveExtraSpaces(result)
        Console.WriteLine(cleaned)
    End Sub

End Module



' run:
'
' abc xyz  abc abc abc
' abc xyz abc abc abc
'

 



answered Feb 15 by avibootz
edited Feb 16 by avibootz

Related questions

...