在此上下文中定义的单词是字母或数字。但是,像\ 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