using System;namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            string s = "1,12,123,1234,123,12,1";
            string str=s;
            for (int i = 0; i < 5; i++)
            {
                str = s.Substring(str.IndexOf(',')+1,str.Length-1);
                Console.WriteLine(str);
            }
            Console.Read();
        }
    }
}
C# Substring()越界问题

解决方案 »

  1.   

                    str = str.Substring(str.IndexOf(',') + 1, str.Length - 1 - str.IndexOf(','));
      

  2.   

    我不知道楼主做这个的具体意义是什么,但是我知道,越界了。
    str = s.Substring(str.IndexOf(',')+1,str.Length-1);
    中,
    str.IndexOf(',') // value:“1”。再加“1”,得“2”。
    本来总字符串才有“22”。
    从“2”开始,最多有 “20”个了,str.Length-1(“21”)那不是越界了?
      

  3.   

    你想干嘛呢?
    是不是按逗号分别输出每个数字呢?        static void Main(string[] args)
            {
                string s = "1,12,123,1234,123,12,1";
                string[] str=s.Split(',');
                for (int i = 0; i < str.Length; i++)
                {
                     Console.WriteLine(str[i]);
                }
                Console.Read();
            }
      

  4.   

     str = s.Substring(str.IndexOf(',')+1,str.Length-1);
    subtring(int i,int j)第二个参数是表示取的个数,不是最后一位的索引
      

  5.   

    string s = "1,12,123,1234,123,12,1";
    foreach (string item in s.Split(','))
        Console.WriteLine(item);
      

  6.   

    建议这样
    string s = "1,12,123,1234,123,12,1";
    string[] items=s.Split(',');
     foreach (string item in items)
         Console.WriteLine(item);
    不然重复调用Split方法
      

  7.   

    using System;namespace ConsoleApplication3
    {
        class Program
        {
            static void Main(string[] args)
            {
                string s = "1,12,123,1234,123,12,1";
                string str=s;
                for (int i = 0; i < 5; i++)
                {
                    str = s.Substring(str.IndexOf(','),str.Length-1);
                    Console.WriteLine(str);
                }
                Console.Read();
            }
        }
    }