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 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 RemoveLastN(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 = RemoveLastN(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 2 hours ago by avibootz
...