Chillu
Chillu

Reputation: 3

How do I split a string to be placed in multiple textboxes?

What I am trying to do is split a string, depending on its length, so I can assign certain sections of it, to different textboxes.

if (str.Length <= 2)
{
    textbox1.Text = str; //(the first textbox is 2 characters long, so this is fine)
}
else if() //this is where I need to split the first two characters 
          //into the first textbox, then the next 2 into a second 
          //textbox, than anything left over into the third textbox

Say the value of the string is 123456789, I would want 89 in the first box, 67 in the second, and 12345 in the third, if that makes sense.

Upvotes: 0

Views: 1674

Answers (3)

Vlad Bezden
Vlad Bezden

Reputation: 89547

Here is the LinqPad Working Code:

void Main()
{
    string theString = "123456789";

    theString.Substring(theString.Length - 2, 2).Dump();
    theString.Substring(theString.Length - 4, 2).Dump();
    theString.Substring(0, theString.Length - 4).Dump();
}

Upvotes: 2

Ry-
Ry-

Reputation: 224904

Something like this?

string theString = "123456789";

System.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex("^(.+?)(.{1,2}?)?(.{1,2})$");
System.Text.RegularExpressions.Match m = re.Match(theString)

this.TextBox1.Text = m.Groups[3].Value
this.TextBox2.Text = m.Groups[2].Value
this.TextBox3.Text = m.Groups[1].Value

Edit: Oh, you're going backwards. Fixed.

Edit 2: I'm sick of Substring and math :)

Upvotes: 1

ulrichb
ulrichb

Reputation: 20054

You can use String.Substring():

"123456789".Substring(0, 2);    => "12"
"123456789".Substring(2, 2);    => "34"
"123456789".Substring(4);       => "56789"

Upvotes: 2

Related Questions