我想提取字符串的第一个200个字,有时我得到以下错误:“索引和长度必须引用在字符串中的位置”错误
"Index and length must refer to a location within the string. Parameter name: length"
的代码是:
int i = GetIndex(fullarticle, 200);
string result = fullarticle.Substring(0, i);
我该如何解决这个问题?
我想提取字符串的第一个200个字,有时我得到以下错误:“索引和长度必须引用在字符串中的位置”错误
"Index and length must refer to a location within the string. Parameter name: length"
的代码是:
int i = GetIndex(fullarticle, 200);
string result = fullarticle.Substring(0, i);
我该如何解决这个问题?
看来安全承担错误是来自string.Substring未来200
startIndex + length > given.Length
或startIndex < 0
或length < 0
,GetIndex
返回的值大于fullarticle.Length
或负数时会得到此错误。该错误存在于GetIndex
,所以如果你想继续使用你的代码,你应该发布代码GetIndex
以得到最好的答案。 如果你达不同的东西,你可以试试这个:
static string GetShortIntroduction(string phrase, int words)
{
// simple word count assuming spaces represent word boundaries
return string.Join(" ", phrase.Split().Take(words));
}
看起来像我比整个fullarticle长度大。检查你的GetIndex函数。
这可能是因为字符串中有不足200个字而可能来自GetIndex
返回i
的值大于fullarticle
中的字符数。由于错误的例子
"s".Substring(0,2)
抛出
ArgumentOutOfRangeException: Index and length must refer to a location within the string. Parameter name: length
如果你的目的是要起床在字符串中的第200个字,你就需要检查
我把它降到150,我仍然得到:索引和长度必须指向字符串中的位置。 参数名称:长度 – 2013-02-14 18:34:08
代码没有试图获得200个字符,它试图获得200 *字*。此外,您的解决方法是错误的,请参阅我对史蒂夫答案的评论。 – 2013-02-14 18:34:14
@KonradRudolph我的不好,我错误地认为OP的意思是字符:)更新。关于隐藏**错误,我认为这取决于该方法正在做什么的背后的意图以及可以对输入做出的假设。在某些情况下,我同意隐藏错误可能不好,在其他情况下我不会:) – 2013-02-14 18:35:50
它超出范围为您的字符串短于200个字符
为了弥补你可以使用Math.Min
它会挑选字符串长度和200之间的较低值。
fullarticle.Substring(0, Math.Min(fullarticle.Length, 200));
希望这可以为您节省一些时间。
错误消息包含您需要的所有信息。很明显,错误在'GetIndex'函数中。 – 2013-02-14 18:32:45
你说你想要200个单词。如果你的字符串少于200字,会发生什么?你能显示GetIndex的代码吗? – Steve 2013-02-14 18:40:52