2014-05-13 39 views
-5

我有一個文本文件,我需要比較everyline的前8個字符,並將這些行作爲一行添加到匹配的位置。我使用的邏輯是從每行開始第一和比較它的其餘行,然後移動到第二行,並執行相同的最後一行。但是當我嘗試通過其他行進行循環比較我得到錯誤「索引和長度必須指向位置在字符串內「。比較文本文件中的字符串

請指教,看下面的代碼。

while ((line1 = fileread.ReadLine()) != null) 
{ 
    counter2++; 

    while ((line2 =fileread.ReadLine()) != null) 
    {       
     if (line1.Substring(0, 8) == line2.Substring(0, 8)) 
     { 
      line1 = line1 + " " + line2; 
     } 
     counter3++; 
    }      

    filewrite.WriteLine(line1); 
    counter1++; 
} 
+5

提示:當一行少於8個字符時會發生什麼? – Rik

+0

檢查字符串的Length屬性... – rene

+0

提示2:使用緩衝區。不要在您從中讀取的同一個循環中寫入文件,否則可能會遇到一些意外結果。 –

回答

0

您需要檢查STE字符串的長度使用Substring之前,使用Length屬性。

while ((line2 =fileread.ReadLine()) != null) 
{   
    if (line1.Length >=8 && lines2.Length >=8 && 
     line1.Substring(0, 8) == line2.Substring(0, 8)) 
    { 
     line1 = line1 + " " + line2; 
    } 
    counter3++; 
}   
+0

非常感謝,問題是與長度 –