Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
539 views
in Technique[技术] by (71.8m points)

c# - 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";
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...