我正在嘗試讀取文本文件並計算某個字符串出現的次數。這是我到目前爲止有:如何統計字符串內子字符串的數量
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