Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
552 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...