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.
You can use String.Substring():
"123456789".Substring(0, 2); => "12"
"123456789".Substring(2, 2); => "34"
"123456789".Substring(4); => "56789"
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();
}
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 :)
精彩评论