在此上下文中定義的單詞是字母或數字。但是,像\ 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();
我會檢查你的循環索引 – TGH 2013-03-22 01:59:18
你確定它在索引聲明,而不是在Line.Length?在你的while語句中,你正在檢查sr.Readline()是否爲空,但是你正在再次讀取另一行,它可能在文件的末尾。 – 2013-03-22 02:01:32