2013-03-22 126 views
0

在此上下文中定義的單詞是字母或數字。但是,像\ n這樣的內容不被視爲一個詞。計算文件中字的數量

下面在我的代碼中,我試圖計算文件中的字數,但在for循環的局部變量聲明中,我收到錯誤Null Reference exception

我不知道爲什麼我得到這個錯誤。我得到的每行的變量行等於空不應該發生,因爲文本文件沒有在它有一個字的「Hello World」 ..

StreamReader sr = new StreamReader(filePath); 
while (sr.ReadLine()!=null) 
{ 
    Line =sr.ReadLine(); 
    for (**int i = 1**; i < (Line.Length+1); i++) 
    { 
     if (Char.IsLetterOrDigit(Line[i]) == true && Char.IsLetterOrDigit(Line[i - 1]) == true) 
     { 
      if (LetterRecent == false) 
      { 
       wordCount = wordCount + 1; 
      } 
      LetterRecent = true; 
     } 
     else 
     { 
      LetterRecent = false; 
     } 
    } 
} 

sr.Close(); 
+0

我會檢查你的循環索引 – TGH 2013-03-22 01:59:18

+0

你確定它在索引聲明,而不是在Line.Length?在你的while語句中,你正在檢查sr.Readline()是否爲空,但是你正在再次讀取另一行,它可能在文件的末尾。 – 2013-03-22 02:01:32

回答

0

您是通過調用sr.ReadLine()兩次丟棄文件中的行的一半。如果您在while語句中讀取文件的最後一行,則對Line.Length的調用將拋出空引用異常。

試試這個:

var wordCount = 0; 
var line = sr.ReadLine(); 
while(line != null) { 
    for(var i = 1; i < line.Length; i++) { 
    // Count words 
    } 
    line = sr.ReadLine(); 
} 
+0

這是我跟隨@reins觀察ReadLine()被調用兩次後獲得的相同解決方案。 – 2013-03-22 02:13:30

3

你正在做的ReadLine()的兩倍。

你可以這樣做:

count = 0; 
while (line = sr.ReadLine()) { 
    char oldChar = 0; 
    for (char c in line) { 
    if (c != oldChar && Char.IsLetterOrDigit(c)) count++; 
    oldChar = c; 
    } 
} 
+0

這可能是原因,因爲我只在textfile中有一個詞是「hello world」,我怎麼能讓這個工作沒有ReadLine()被調用兩次? – 2013-03-22 02:03:29

+0

@SdfsdSdf,「你好世界」是2個單詞不是一個。 – 2013-03-22 02:14:30

+0

@ sa_ddam213抱歉,這就是我的意思。 – 2013-03-22 02:46:42

0

你需要使用它之前宣佈wordCount

Int wordCount = 0; 
while (sr.ReadLine()!=null) 
    { 
0

更新您的循環條件是這樣的:

while (sr.Peek() >= 0) 
{ 
    Line = sr.ReadLine(); 
}