如何将一个字符串分隔为两个字符串
本文关键字:字符串 两个 分隔 一个 | 更新日期: 2023-09-27 18:22:14
我使用的是C#.NET和Windows CE Compact Framework。我有一个代码,其中应该将一个字符串分隔为两个文本框。
textbox1 = ID
textbox2 = quantity
string BarcodeValue= "+0000010901321 JN061704Z00";
textbox1.text = BarcodeValue.Remove(0, BarcodeValue.Length - BarcodeValue.IndexOf(' ') + 2);
//Output: JN061704Z00
textbox2.text = BarcodeValue.Remove(10, 0).TrimStart('+').TrimStart('0');
//Output: should be 1090 but I am getting a wrong output: 10901321 JN061704Z00
//Please take note that 1090 can be any number, can be 999990 or 90 or 1
有人能帮我吗(
谢谢!!
使用Split
方法:
string BarcodeValue = "+0000010901321 JN061704Z00";
var splitted = BarcodeValue.Split(' '); //splits string by space
textbox1.text = splitted[1];
textbox2.text = splitted[0].Remove(10).TrimStart('+').TrimStart('0');
您可能应该在访问拆分长度之前检查它是否为2,以避免出现IndexOutOfBound
异常。
使用Split()
string BarcodeValue= "+0000010901321 JN061704Z00";
string[] tmp = BarcodeValue.Split(' ');
textbox1.text = tmp[1];
textbox2.text= tmp[0].SubString(0,tmp[0].Length-4).TrimStart('+').TrimStart('0');
static void Main(string[] args)
{
string BarcodeValue = "+0000010901321 JN061704Z00";
var text1 = BarcodeValue.Split(' ')[1];
var text2 = BarcodeValue.Split(' ')[0].Remove(10).Trim('+');
Console.WriteLine(text1);
Console.WriteLine(Int32.Parse(text2));
}
结果:
JN061704Z00
1090
上面发布的代码的一个稍好的版本。
string BarcodeValue= "+0000010901321 JN061704Z00";
if(BarcodeValue.Contains(' '))
{
var splitted = BarcodeValue.Split(' ');
textbox1.text = splitted[1];
textbox2.text = splitted[0].TrimStart('+').TrimStart('0');
}
Remove(10,0)
删除零个字符。您希望Remove(10)
删除位置10之后的所有内容。
有关这两个版本,请参阅MSDN。
或者,使用Substring(0,10)
获取前10个字符。
只有当barcodeValue长度始终为常量时,这才有效。
string[] s1 = BarcodeValue.Split(' ');
textBox1.Text = s1[0];
textBox2.Text = s1[1];
string _s = s1[0].Remove(0, 6).Remove(3, 4);
textBox3.Text = _s;
string BarcodeValue = "+0000010901321 JN061704Z00";
var splittedString = BarcodeValue.Split(' ');
TextBox1.Text = splittedString [0].Remove(10).TrimStart('+').TrimStart('0');
TextBox2.Text = splittedString [1];
输出-
TextBox1.Text = 1090
TextBox2.Text = JN061704Z00