Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# System.ArgumentOutOfRangeException:startIndex不能大于字符串的长度_C#_Asp.net Mvc - Fatal编程技术网

C# System.ArgumentOutOfRangeException:startIndex不能大于字符串的长度

C# System.ArgumentOutOfRangeException:startIndex不能大于字符串的长度,c#,asp.net-mvc,C#,Asp.net Mvc,我有这个密码。我正试图检索文本“first program”。考虑到我知道索引是25,字符串的总长度是35 string text="Hello world ! This is my first program"; Response.Write(text.SubString(25,35)); 但我在运行时遇到错误“System.ArgumentOutOfRangeException:startIndex不能大于字符串长度”的参数为: 您试图在第26个字符(startIndex是以零为基础的)

我有这个密码。我正试图检索文本“first program”。考虑到我知道索引是25,字符串的总长度是35

string text="Hello world ! This is my first program";

Response.Write(text.SubString(25,35));
但我在运行时遇到错误“System.ArgumentOutOfRangeException:startIndex不能大于字符串长度”

的参数为:

您试图在第26个字符(startIndex是以零为基础的)之后添加35个字符,这超出了范围


如果只想从第25个字符到字符串末尾,请使用
文本。子字符串(24)
字符串的第二个参数。子字符串()是长度,而不是结尾偏移量:

Response.Write(text.Substring(25, 10));

Substring
的第二个参数是您希望子字符串的长度,而不是子字符串的端点
25+35
超出了原始字符串的范围,因此会引发异常。

子字符串的第二个参数是子字符串中的字符数

更简单的方法

int startIndex = 25; // find out startIndex
int endIndex = 35;   // find out endIndex, in this case it is text.Length;
int length = endIndex - startIndex; // always subtract startIndex from the position wherever you want your substring to end i.e. endIndex

// call substring
Response.Write(text.Substring(startIndex,length));     

您可以执行一些操作或调用函数来获取开始/结束索引值。使用这种方法,您不太可能遇到与索引相关的任何问题。

在此期间,您可以使用


(LINQ ElementAt)(ElementAtOrDefault)方法。但是,当指定的索引为负值或不小于序列的大小时,ElementAt扩展方法将抛出System.ArguementOutOfRangeException

第二个参数不应该是子字符串的长度吗?请注意,您还需要有正确的长度参数-如果start+lengthToExtract>字符串的实际长度,您将获得ArgumentOutOfRangeException-请参阅。您可能需要的是文本。SubString(25,13)-13是文本“first program”的长度。我得到一个ArgumentOutOfRangeException,但带有以下消息:“索引和长度必须引用字符串中的位置。参数名称:length”
int startIndex = 25; // find out startIndex
int endIndex = 35;   // find out endIndex, in this case it is text.Length;
int length = endIndex - startIndex; // always subtract startIndex from the position wherever you want your substring to end i.e. endIndex

// call substring
Response.Write(text.Substring(startIndex,length));