Jane Doe Jane Doe - 6 months ago 12
Vb.net Question

How can I display a name in a different sequence using strings?

I'm having trouble with a problem that I was assigned for my Visual Basic 2012 class. The instructions are below. So far, I have it displaying only the first name entered, and nothing else. How can I make it to display both the first name and the last name in the sequence requested?


String Problem: Enter your first and last name in a text box. Take the name and display it in a label box showing the last name, first name.


Text Box Entry: Jane Doe

Label Box: Doe, Jane

The code I have so far is below. Thanks for any help!

Private Sub btndisplay_Click(sender As Object, e As EventArgs) Handles btndisplay.Click
Dim fullname As String
Dim firstname As String
Dim indexnum As Integer
Dim lastname As String

fullname = fulltextbox.Text

indexnum = fullname.IndexOf(" ")

firstname = fullname.Substring(0, indexnum)

firstlabel.Text = firstname
fulltextbox.Focus()
End Sub

Private Sub fulltextbox_TextChanged(sender As Object, e As EventArgs)
firstlabel.Text = String.Empty

fulltextbox.SelectAll()
End Sub

Private Sub btnexit_Click(sender As Object, e As EventArgs) Handles btnexit.Click
Me.Close()
End Sub

Answer

You are on the right track by first determining where the space is located:

indexnum = fullname.IndexOf(" ")

Now based on this index, you can split the string into two strings, firstname and lastname:

firstname = fullname.Substring(0, indexnum)
lastname = fullname.Substring(indexnum+1)

You need to use indexnum+1, instead of indexnum, otherwise you will include the spacing character.

Finally you group them together again by using the string concatenation operator (&):

firstlabel.Text = lastname & ", " & firstname

The final method thus looks like:

Private Sub btndisplay_Click(sender As Object, e As EventArgs) Handles btndisplay.Click
    Dim fullname As String
    Dim firstname As String
    Dim indexnum As Integer
    Dim lastname As String

    fullname = fulltextbox.Text

    indexnum = fullname.IndexOf(" ")

    firstname = fullname.Substring(0, indexnum)
    lastname = fullname.Substring(indexnum+1)

    firstlabel.Text = lastname & ", " & firstname
    fulltextbox.Focus()
End Sub