使用字符串 [] 或字符串列表计算单词?

我试图计算文件中的单词数,要么我做一个 string[] 列表并在取出空格时出错,要么我做普通字符串并在 Splitting String 部分出错,我也想显示三个大多数重复的单词这就是为什么我需要一个所有字符串的列表。


代码如下:


//Reading File


var path = @"D:\Projects\C sharp Course\Working_with_Files\Working_with_Files_1\Text.txt";

List<string> list = new List<string>();

var content = File.ReadAllText(path);

var text = content.Trim();

string[] splitted;


//Splitting String


for (int i = 0; i < text.Length; i++)

{


    splitted = text.Split(',', ' ', '.', '(', ')');          

    list.Add(splitted);

}


//Taking out Whitespaces


for (int i = 0; i < list.Count; i++)

{

    if (string.IsNullOrWhiteSpace(list[i]))

    {

        list.RemoveAt(i);

    }

}


胡说叔叔
浏览 129回答 2
2回答

动漫人物

你的循环似乎没有意义,因为每个循环都会做同样的事情:for (int i = 0; i < text.Length; i++)//You do not use this i!{&nbsp; &nbsp; splitted = text.Split(',', ' ', '.', '(', ')');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; list.Add(splitted);//Will add the same splitted text each time.}我认为您可以删除循环,因为拆分已经拆分了整个文本。string[] splitted = text.Split(',', ' ', '.', '(', ')');&nbsp; &nbsp; &nbsp; &nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP