2013-03-22 73 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(); 
}