【问题标题】:Index and length must refer to a location within the string. Parameter name: length索引和长度必须引用字符串中的位置。参数名称:长度
【发布时间】:2012-05-23 19:10:45
【问题描述】:

我收到此错误:

Index and length must refer to a location within the string.
Parameter name: length

使用此代码:

string a1 = ddlweek.Text.Substring(0, 8);                
string a3 = ddlweek.Text.Substring(10, 14);

这是什么意思?

【问题讨论】:

标签: c# asp.net substring


【解决方案1】:

如果您的字符串 (ddlweek) 的长度为 23 个字符或更少,您将收到此错误:

    string ddlweek = "12345678901234567890123";//This is NOK
    string a1 = ddlweek.Substring(0, 8);                
    string a3 = ddlweek.Substring(10, 14);
    Console.WriteLine("a1="+a1);
    Console.WriteLine("a3="+a3);
    Console.ReadLine();

字符串长度至少应为 24 个字符。 您可以考虑添加if 以确保一切正常..

    string ddlweek = "123456789012345678901234";//This is OK
    string a1 = ddlweek.Substring(0, 8);                
    string a3 = ddlweek.Substring(10, 14);
    Console.WriteLine("a1="+a1);
    Console.WriteLine("a3="+a3);
    Console.ReadLine();

【讨论】:

    【解决方案2】:

    这意味着您的ddlweek.Text 字符串包含的字符数少于您在Substring(index, length) 中要求的字符数。

    例子:

    if (ddlweek.Text.Length >= 8)
        string a1 = ddlweek.Text.Substring(0, 8);  
    

    【讨论】:

      【解决方案3】:

      这只是意味着您要的是一个不存在的 ddlweek 子字符串(即长度超过 24 个字符)。

      【讨论】:

        【解决方案4】:

        当您超过总字符的结束限制时会发生此错误。 例如

                string name = "iLovePakistan"; // Here i want to print only Pakistan
        
                string name2 = name.Substring(5, 150); // this code will throw same error. just replace 150 with name.Length - 5
        
                string name3 = name.Substring(5, name.Length - 5); // i skip firt 5 charchers then name.Length-5 means print rest 8 characters.
        
                string name4 = name.Substring(5, 8); // This will do exactly as name3
                Console.WriteLine(name4);
        

        【讨论】:

          【解决方案5】:
          Substring(startIndex,length);
          

          startIndex :获取您想要获取的第一个值。 0 开始。

          length:你得到的值的大小(你会得到多少位数)。

          string Code = "KN32KLSW";
          string str = Code.Substring(0,2);
          Console.WriteLine("Value : ",str);
          

          在控制台屏幕上:KN

          string str = Code.Substring(3,4);
          Console.WriteLine("Value : ",str);
          

          在控制台屏幕上:2KLS

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2020-09-18
            • 2017-08-28
            • 1970-01-01
            • 1970-01-01
            • 2016-03-15
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多