How to get the last word from string in VB.NET

1 Answer

0 votes
Imports System

Module Program
    Sub Main()
        Dim s As String = "vb.net javascript php c c++ python c#"
        Dim lastWord As String = GetLastWord(s)
        Console.WriteLine("1. " & lastWord)

        lastWord = GetLastWord("")
        Console.WriteLine("2. " & lastWord)

        lastWord = GetLastWord("c#")
        Console.WriteLine("3. " & lastWord)

        lastWord = GetLastWord("c c++ java ")
        Console.WriteLine("4. " & lastWord)

        lastWord = GetLastWord("  ")
        Console.WriteLine("5. " & lastWord)
    End Sub

    Function GetLastWord(input As String) As String
        If String.IsNullOrWhiteSpace(input) Then
            Return ""
        End If

        input = input.Trim() ' remove leading/trailing spaces

        Dim pos As Integer = input.LastIndexOf(" "c)
        If pos > -1 Then
            Return input.Substring(pos + 1)
        Else
            Return input
        End If
    End Function
End Module


' run:
'
' 1. c#
' 2. 
' 3. c#
' 4. java
' 5.  
' 

 



answered Sep 8, 2019 by avibootz
edited Mar 27 by avibootz
...