9

我收到此错误:

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);

这是什么意思?

4

5 回答 5

15

如果您的字符串 (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();
于 2012-05-16T08:56:14.230 回答
7

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

例子:

if (ddlweek.Text.Length >= 8)
    string a1 = ddlweek.Text.Substring(0, 8);  
于 2012-05-16T08:49:37.510 回答
3

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

        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);
于 2014-05-27T10:58:43.967 回答
3

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

于 2012-05-16T08:48:06.167 回答
1
Substring(startIndex,length);

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

长度:您获得的值的大小(您将获得多少位数)。

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

于 2020-03-13T11:23:42.183 回答