如何分割字符串,每个字分配到一个新的变量? [英] How to split a string and assign each word to a new variable?

查看:112
本文介绍了如何分割字符串,每个字分配到一个新的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在做一个信用卡处理形式。有问题的字段名称:(第一个和最后一个)



你会一些C#代码的样子,将采取文字从一个文本框,并把它分解,然后分配每个字(在此情况下的姓和名)分成两个新的字符串



例如 txtName.Text =李四



拆分后

 字符串FNAME =约翰; 

串LName的=李四;


解决方案

您可以在字符或字符串文本分成一个字符串数组,然后拉出名称的各个部分从数组中。像这样:

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

串的firstName = nameParts [0];
串的lastName = nameParts [1];



但是,为什么不只是有一个单独的文本框的名称各部分?如果有人有什么把他们的全名在文本框中(即你有三部分,而不是两个)。


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";

解决方案

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

这篇关于如何分割字符串,每个字分配到一个新的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆