c# - 计算文本文件中的单词数

标签 c# .net regex

我正在尝试计算文本文件中的单词数,即开始。

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/

相关文章:

javascript - Javascript 中的字符串模式匹配

javascript - 通过 PHP session 进行服务器身份验证

c# - 使用 C# 线程化 : Calling back to main thread in a . NET Windows 服务

c# - 正则表达式 - 匹配一个字符串,但只匹配下一个单词不是 'x' 的地方

.net - 在 VB.NET 中访问 REST WebService

c# - 对将 HttpResponse 对象作为参数的方法进行单元测试。输出流不可用

mysql - 查找具有 case 句子结构的字符串 (UC lc $word)

c# - SQL 本地数据库未连接到其他计算机

c# - 接受 List<T> 的通用方法

c# - 将DataMemberAttribute 放在接口(interface)成员上是什么意思?