2013-02-14 109 views
-2

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

我該如何解決這個問題?

+0

錯誤消息包含您需要的所有信息。很明顯,錯誤在'GetIndex'函數中。 – 2013-02-14 18:32:45

+1

你說你想要200個單詞。如果你的字符串少於200字,會發生什麼?你能顯示GetIndex的代碼嗎? – Steve 2013-02-14 18:40:52

回答

2

看來安全承擔錯誤是來自string.Substring未來200

  • 子。假設您在startIndex + length > given.LengthstartIndex < 0length < 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)); 
    } 
    
  • 0

    看起來像我比整個fullarticle長度大。檢查你的GetIndex函數。

    1

    這可能是因爲字符串中有不足200個字而可能來自GetIndex返回i的值大於fullarticle中的字符數。由於錯誤的例子

    "s".Substring(0,2) 
    

    拋出

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

    如果你的目的是要起牀在字符串中的第200個字,你就需要檢查

    1. 字符串不爲空
    2. 字符串中的字數;如果是小於200分的話,那應該是你最大的索引,否則使用基於2
    +0

    我把它降到150,我仍然得到:索引和長度必須指向字符串中的位置。 參數名稱:長度 – 2013-02-14 18:34:08

    +2

    代碼沒有試圖獲得200個字符,它試圖獲得200 *字*。此外,您的解決方法是錯誤的,請參閱我對史蒂夫答案的評論。 – 2013-02-14 18:34:14

    +0

    @KonradRudolph我的不好,我錯誤地認爲OP的意思是字符:)更新。關於隱藏**錯誤,我認爲這取決於該方法正在做什麼的背後的意圖以及可以對輸入做出的假設。在某些情況下,我同意隱藏錯誤可能不好,在其他情況下我不會:) – 2013-02-14 18:35:50

    5

    它超出範圍爲您的字符串短於200個字符

    爲了彌補你可以使用Math.Min它會挑選字符串長度和200之間的較低值。

    fullarticle.Substring(0, Math.Min(fullarticle.Length, 200)); 
    

    希望這可以爲您節省一些時間。

    相關問題