quick question

propagandhi

Member
Joined
Feb 20, 2005
Messages
18
Programming Experience
Beginner
suppose i wanted to take a name from a text box and seperate the full name into strFirst and strLast, and the display the name reformated.

I know that in order to display the name reformated i would do something like:

dim strFirst as string
dim strLast as string
dim strName as string
dim strNew as string

strName = txtName.text.toString
*
*strFirst =
*
*strLast =
*
strNew = (strLast & "," & " " & strFirst)

lblNew.text = strNew

My problem is with seperating the first and last names. I have tried working with the .split function but have had no success.

Any help is greatly appreciated,
Steve
 

Paszt

Staff member
Joined
Jun 3, 2004
Messages
1,500
Location
Raleigh, NC - USA
Programming Experience
Beginner
You can use the split function with a space as the parameter.
You can also use the SubString method of the String structure.
Both methods assume that the first and last name are seperated by a space.
Here's some sample code:
VB.NET:
Dim strFirst, strLast As String
Dim ar() As String
ar = txtname.Text.Split(" ".ToCharArray)
strFirst = ar(0)
strLast = ar(1)
Stop
Dim intSpacePos As Integer = txtname.Text.IndexOf(" ".ToCharArray)
strFirst = txtname.Text.Substring(0, intSpacePos)
strLast = txtname.Text.Substring(intSpacePos + 1, _
  txtname.Text.Length - intSpacePos - 1)
Stop
Welcome to the furum :)
Please consider using more descriptive titles when posting questions. It helps during searches. :)
 
Last edited:

malitice

Active member
Joined
Feb 20, 2005
Messages
41
Programming Experience
1-3
Lucky for you I just did something with that earlier...

VB.NET:
		If InStr(textbox1.Text, ",", CompareMethod.Binary) Then
		Else
			Dim x As Integer
			Dim splitout = Split(textbox1.Text, " ")
			textbox1.Text = splitout(UBound(splitout)) & ","
			For x = 0 To UBound(splitout) - 1
			    textbox1.Text &= " " & splitout(x)
			Next x
		 end if

A brief explanation:
If InStr(textbox1.Text, ",", CompareMethod.Binary) Then
Else

Checks to see if their is a comma in the box, if their is a comma nothing is done otherwise:

Dim x As Integer
Dim splitout = Split(textbox1.Text, " ")
textbox1.Text = splitout(UBound(splitout)) & ","
For x = 0 To UBound(splitout) - 1
textbox1.Text &= " " & splitout(x)
Next x

Splits the text by the spaces, takes the last item and makes it the first, adds a comma and then adds the remaining names.

This allows it to not only work on names like John Smith (becomes Smith, John), but also Mary Ann Lou Smith (Smith, Mary Ann Lou) and for names that are correctly formatted (Smith, John) it just ignores it.
 
Top Bottom