我正在尝试读取文本文件并计算某个字符串出现的次数。这是我到目前为止有:如何统计字符串内子字符串的数量
System.IO.StreamReader file = new System.IO.StreamReader("C:\\Users\\Test\\Documents\\Sample.txt");
while ((line = file.ReadLine()) != null) {
Console.WriteLine(line);
counter = Regex.Matches(line, "the", RegexOptions.IgnoreCase).Count;
}
Console.WriteLine(counter);
file.Close();
// Suspend the screen.
Console.ReadLine();
所以我想找到所有包含在其中“的”字符串的话,但我没有得到正确的计数。我希望它也能像“枯萎”等词语一样统计“the”,而不仅仅是“the”这个词。我发现的问题是,当txt文件在它们之间包含不同的段落和空格时,它会错过这些单词。当我在段落之间没有空格时,它似乎工作。我可以做些什么来解决这个问题?
这就是我所说的一段空间:
Sample text Sample text Sample text Sample text Sample text.
Sample text Sample text Sample text Sample text Sample text .
但是,如果我将它们合并这样它的工作原理:
Sample text Sample text Sample text Sample text Sample text.Sample text Sample text Sample text Sample text Sample text.
每个循环都要设置计数。你想增加计数。 'counter + = ....' – Nkosi