开发者

Split text typed into a text box into labels on another form

I have already been able to split a first name and a last name. But the problem I am having is if someone decides to type in a middle initial or a middle name? Anyone know how I can go about doing this?

Here is the code I have so far:

//Name Split
var fullname = strTextBox;
var names = 开发者_如何学运维fullname.Split(' ');           
label3.Text = names[0];
label5.Text = names[1] + " " + names[2];

This code works if the person types in a middle initial and a a last name. But is the user only types in a first and last name, the names[2] gives me the error since it cannot find another partition.

I would say that I have spent at least 10 hours trying to figure out a conditional to get this to work, but have not gotten it yet.

Here is one of the many conditionals I have tried:

//Name Split
var fullname = strTextBox;
var names = fullname.Split(' ');
if (fullname.Contains (> 1 (' '))
{
    label3.Text = names[0]; // first
    label5.Text = names[1] + " " + names[2]; // middle initial
}
else
{
    label3.Text = names[0];
    label5.Text = names[1];
}


Personally I'd go with a seperate text box for each piece of data I want to collect.

The main reason being that you can't accurately predict what the user is going to enter into your "fullname" text box. There's just too many variations.

Consider:

Jamie Dixon
Jamie O Dixon
Dixon, Jamie O
Dixon, Jamie
Jamie O P J Dixon

While there are a finite number of combinations, what you can't really predict is how much and in what order the user will enter the details.


It's not a nice solution what you got, would split it up into two text boxes, but if you want this should bring the desired effect:

var fullname = strTextBox;
var names = fullname.Split(' ');

if(names.Count()<2)
{
  // throw an error here, because user did not enter first + lastname
}

label3.Text = names[0];
label5.Text = (names.Count() > 2 ? names[1] + " " + names[2] : names[1]);


try this:

label5.Text = string.Format("{0} {1}", (names.Length == 2 ? "" : names[1]), 
                names.Last()).Trim();


Try this. This will help whatever names you have at the end.

        //string fullname = "";
        //string fullname = "first";
        //string fullname = "first last";
        string fullname = "first middle last";
        //string fullname = "first middle last extra-last";
        string[] names = fullname.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);

        if (names.Length > 0)
        {
            string firstName = names[0];
            string lastNameWithInitial = string.Join(" ", names, 1, names.Length - 1);
        }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜