How to remove the last word from a string in VB.NET

1 Answer

0 votes
Imports System

Public Class RemoveLastWordProgram

    ' Removes the last word from a space‑separated string.
    ' If there are no words, returns an empty string.
    ' If there is only one word, returns that word unchanged.
	Public Shared Function RemoveLastWord(input As String) As String

        ' Trim trailing spaces so the last "word" is real text
        Dim trimmed As String = input.TrimEnd()

        ' Find the last space in the trimmed string
        Dim index As Integer = trimmed.LastIndexOf(" "c)

        ' No space found:
        ' - if trimmed is empty → no words → return empty string
        ' - otherwise → single word → return it unchanged
        If index = -1 Then
            Return trimmed
        End If

        ' Return everything before the last space
        Return trimmed.Substring(0, index)
    End Function

    Public Shared Sub Main(args As String())

        Dim s As String = "c# vb.net c c++ java"

        Dim result As String = RemoveLastWord(s)
        Console.WriteLine("1. " & result)

        result = RemoveLastWord("")
        Console.WriteLine("2. " & result)

        result = RemoveLastWord("c#")
        Console.WriteLine("3. " & result)

        result = RemoveLastWord("c c++ java ")
        Console.WriteLine("4. " & result)

        result = RemoveLastWord("  ")
        Console.WriteLine("5. " & result)
    End Sub

End Class



' run:
'
' 1. c# vb.net c c++
' 2. 
' 3. c#
' 4. c c++
' 5. 
'

 



answered Feb 24, 2017 by avibootz
edited Mar 27 by avibootz
...