如何将一个字符串分成2个字符串

时间:2013-07-12 07:14:39

标签: c# .net string trim

我正在使用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

有人可以帮我这个吗? :((

谢谢!

7 个答案:

答案 0 :(得分:5)

使用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异常。

答案 1 :(得分:4)

使用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');

答案 2 :(得分:2)

    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

答案 3 :(得分:1)

Remove(10,0)删除零个字符。您希望Remove(10)删除位置10之后的所有内容。

有关这两个版本,请参阅MSDN

或者,使用Substring(0,10)获取前10个字符。

答案 4 :(得分:1)

上面发布的代码稍微好一些。

          string BarcodeValue= "+0000010901321 JN061704Z00";
           if(BarcodeValue.Contains(' '))
           {
              var splitted = BarcodeValue.Split(' ');

              textbox1.text = splitted[1];

              textbox2.text = splitted[0].TrimStart('+').TrimStart('0');
            }

答案 5 :(得分:0)

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

答案 6 :(得分:0)

仅当barcodeValue长度始终为const时才有效。

    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;