我如何分割字符串放置在多个文本框
本文关键字:文本 字符串 何分割 分割 | 更新日期: 2023-09-27 18:01:58
我要做的是分割字符串,这取决于它的长度,所以我可以将它的某些部分分配给不同的文本框。
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
假设字符串的值是123456789,我希望89在第一个框中,67在第二个框中,12345在第三个框中,如果这样有意义的话。
可以使用String.Substring():
"123456789".Substring(0, 2); => "12"
"123456789".Substring(2, 2); => "34"
"123456789".Substring(4); => "56789"
LinqPad工作代码:
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();
}
像这样?
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
编辑:哦,你在倒退。固定的。编辑2:我厌倦了Substring
和数学:)