The Muffin Man
The Muffin Man

Reputation: 20004

How to split a string and assign each word to a new variable?

I'm making a credit card processing form. The field in question is Name: (first and last).

What would some C# code look like that would take the text from a text box and split it, then assign each word (in this case first and last name) into two new strings?

E.g. txtName.Text = "John Doe"

After split

string fName = "John";

string LName = "Doe";

Upvotes: 1

Views: 12066

Answers (4)

Umair Hashmi
Umair Hashmi

Reputation: 761

it helps you to split a string in a part

string FullMobileNumber = "+92-342-1234567"; string[] mobile = FullMobileNumber.Split('-'); _txtCountryCodeMobile.Text = mobile[0]; _MobileCodeDropDown.SelectedValue = mobile[1]; _txtEmployeeMobileNumber.Text = mobile[2];

Upvotes: 1

Cᴏʀʏ
Cᴏʀʏ

Reputation: 107586

You can split the text on a character or string into a string array, and then pull the individual parts of the name out of the array. Like so:

string[] nameParts = txtName.Text.Split(' ');

string firstName = nameParts[0];
string lastName = nameParts[1];

But why not just have a separate text box for each part of the name? What if somebody puts their full name in the text box (i.e. you'd have three parts, not just two).

Upvotes: 7

jwsample
jwsample

Reputation: 2411

string[] names = txtName.Text.Split(' ');
string fName = names[0];
string LName = names[1];

Upvotes: 1

Ed Swangren
Ed Swangren

Reputation: 124752

String.Split returns an array, so... just assign from the array.

Upvotes: 0

Related Questions