Kuyo Kuyo - 5 months ago 18
Vb.net Question

Getting a substring text from a string in VB.NET

Lets say I have a text

Howard Johnson, 21 (USA)


I want to get the substring of the text
Johnson
.

I could do this with
InStr
and
Microsoft.VisualBasic.Left
Or
Mid
, But I always found this method rather tedious and I want to know if there is another easier method to do this.

Dim myText As String = "Howard Johnson, 21 (USA)"
Dim textIWant As String = InStr(1, myText, Chr(32))
Dim LastName As String = Mid(myText, textIWant + 1, textIWant)
'Output: Johnson


Any suggestions?

Answer

Try this code - it uses the IndexOf function of a String to locate the first instance of a character within that String.

For a surname, the example code is looking for the first space and the first comma and taking the text in between. The assumption is that the surname is always delimited that way.

For the country, the example code is looking for the first ( and the last ) and taking the text in between. The assumption is that the country is always in round brackets.

Here's the code:

Sub Main()

    Dim Input As String
    Dim Surname As String
    Dim Country As String

    Input = "Howard Johnson, 21 (USA)"
    Surname = Input.Substring(Input.IndexOf(" ") + 1, Input.IndexOf(",") - Input.IndexOf(" ") - 1)
    Country = Input.Substring(Input.IndexOf("(") + 1, Input.IndexOf(")") - Input.IndexOf("(") - 1)

    Console.WriteLine(Surname)
    Console.WriteLine(Country)

    Console.ReadKey()

End Sub

It will also work for people who have spaces in their surname e.g.:

Input = "Albert del Rosario, 75 (Phillipines)"
Surname = Input.Substring(Input.IndexOf(" ") + 1, Input.IndexOf(",") - Input.IndexOf(" ") - 1)

Will output

del Rosario