我想提取字符串的第一個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