比如我有如下一字符串string test="A,B,C,D,E,F,G";
怎样得到第3个逗号之前和之后的字符串赋给不同的变量?test1="A,B,C";
test2="D,E,F,G";只能用正则表达式?

解决方案 »

  1.   

    first you just set the number of , into n, like this            int n = 3;
                string test = "A,B,C,D,E,F,G";
                string test1 = test.Split(',').Take(n).Aggregate((a, b) => a + "," + b);
                string test2 = test.Split(',').Skip(n).Aggregate((a, b) => a + "," + b);
                Console.WriteLine(test1);
                Console.WriteLine(test2);
      

  2.   

    楼上是一种办法,
    另一种办法:
    string test = "A,B,C,D,E,F,G";
    string test1 = test.Substring(0, 5);
    string test2 = test.Substring(6, 7);
    或者:string test="A,B,C,D,E,F,G";
    int n = 5;
    string test1 = test.Substring(0, n);
    string test2 = test.Substring(n + 1, test.Length-n-1);
    Response.Write(test1 + "-" + test2);
      

  3.   

    给个正则的
    int n = 3;
    string test = "A,BC,B,DE,E,F,G";
    Regex reg = new Regex(@"(?<=^(?:[^,]+,){" + (n-1) + @"}[^,]+),");
    string[] result = reg.Split(test);
    foreach(string s in result)
    {
        richTextBox2.Text += s + "\n";
    }
      

  4.   

    第一种方法
    int n = 3;
    string test = "A,B,C,D,E,F,G";
    string test1 = test.Split(',').Take(n).Aggregate((a, b) => a + "," + b);
    string test2 = test.Split(',').Skip(n).Aggregate((a, b) => a + "," + b);
    Console.WriteLine(test1);
    Console.WriteLine(test2);
    第二种方法
    string test = "A,B,C,D,E,F,G";
    string test1 = test.Substring(0, 5);
    string test2 = test.Substring(6, 7);
    或者:string test="A,B,C,D,E,F,G";
    int n = 5;
    string test1 = test.Substring(0, n);
    string test2 = test.Substring(n + 1, test.Length-n-1);
    Response.Write(test1 + "-" + test2);
      

  5.   

    string test="A,B,C,D,E,F,G";
    int tmp = test.IndexOf(",",3);
    string test1 = test.Substring(0, tmp+1);
    string test2 = test.Substring(tmp);
    Response.Write(test1 + "-" + test2);
      

  6.   

    郁闷 问之前没好好查 原来IndexOf可以String.IndexOf 方法 (Char, [startIndex], [count])报告指定字符在此实例中的第一个匹配项的索引。搜索从指定字符位置开始,并检查指定数量的字符位置。