我正在尝试计算文本文件中的单词数,即开始。
This is a test of the word count program. This is only a test. If your program works successfully, you should calculate that there are 30 words in this file.
我正在使用 StreamReader 将文件中的所有内容放入字符串中,然后使用 .Split 方法获取单个单词的数量,但在编译和运行程序时我总是得到错误的值。
using System;
using System.IO;
class WordCounter
{
static void Main()
{
string inFileName = null;
Console.WriteLine("Enter the name of the file to process:");
inFileName = Console.ReadLine();
StreamReader sr = new StreamReader(inFileName);
int counter = 0;
string delim = " ,.";
string[] fields = null;
string line = null;
while(!sr.EndOfStream)
{
line = sr.ReadLine();
}
fields = line.Split(delim.ToCharArray());
for(int i = 0; i < fields.Length; i++)
{
counter++;
}
sr.Close();
Console.WriteLine("The word count is {0}", counter);
}
}
最佳答案
尽量使用正则表达式,例如:
int count = Regex.Matches(input, @"\b\w+\b").Count;
关于c# - 计算文本文件中的单词数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13242328/