Splitting Text

iAaron

New member
Joined
Dec 10, 2007
Messages
2
Programming Experience
1-3
Hi everyone, I'm new here so sorry if this is in the wrong place. :eek:

I am currently using VB.net and am having trouble splitting a text input.

Basically, a user types their first & last name into a single text box. I want to save their first name in a variable, and their last name in another variable.

I am trying to do this using the InStr method but am having difficulties. There is a space between the 2 names so I am using the InStr method to detect this but it's not working. Would anyone be able to help me? :confused:

Thanks for reading! Aaron R.
 
It's better to use two TextBoxes instead of one to get the first and last name from the user. You can split a given string using the Split method.

For eg,

VB.NET:
TextBox1.Text.Split(" ")

You can pass the delimiter as an argument to the Split method and it will return an array of strings. In your case the separator/delimiter is a space.
 
The way I would probably do this, and I don't know if this is the most correct or easiest way, is like this:

VB.NET:
Dim strFirstName As String
Dim strLastName As String

strFirstName = txtName.Text.Split(" ")(0)
strLastName = txtName.Text.Split(" ")(1)

This way, txtName is your textbox. By using the .Split property of it you can seperate it on the space and assign the names to their different variables. Again, I don't know that this is the best way, but this is how i would do it. If anyone has a more correct way feel free to correct me.
 
It's better to use two TextBoxes instead of one to get the first and last name from the user.

I know, but unfortunatley it's a user requirement to do it this way. :rolleyes:

Thanks both of you, that method works great.
 
VB.NET:
strFirstName = txtName.Text.Split(" ")(0)
strLastName = txtName.Text.Split(" ")(1)
feel free to correct me.
Why would you split twice to get same information? All you have to do is to declare a string array to hold the return value of the String.Split function method, then use this array to get the array items.
 
I had asked the same question last week in another forum, I needed to split the FullName formatted as LastName, FirstName into two strings. This is the soultion I got from one of the experienced users in the forum.

VB.NET:
Dim FullName As String = txtFullName.Text
Dim LastName As String = String.Empty
Dim FirstName As String = String.Empty
LastName = FullName.Substring(0, FullName.IndexOf(" "c)).Replace(",", String.Empty).Trim
FirstName = FullName.Substring(FullName.IndexOf(" "c)).Trim
Me.txtFirstame.Text = FirstName
Me.txtLAstName = LastName

Hope this helps
CoachBarker
 
Back
Top