C# 使用字符串[]或字符串列表计算单词?
我试图计算文件中的单词,或者我做了一个字符串[]列表并在删除空格时出错,或者我做了普通字符串并在拆分字符串部分出错,而且我想显示三个最重复的单词,这就是为什么我需要一个所有字符串的列表 代码如下:C# 使用字符串[]或字符串列表计算单词?,c#,string,counting,words,C#,String,Counting,Words,我试图计算文件中的单词,或者我做了一个字符串[]列表并在删除空格时出错,或者我做了普通字符串并在拆分字符串部分出错,而且我想显示三个最重复的单词,这就是为什么我需要一个所有字符串的列表 代码如下: //Reading File var path = @"D:\Projects\C sharp Course\Working_with_Files\Working_with_Files_1\Text.txt"; List<string> list = new List<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);
}
}
//读取文件
var path=@“D:\Projects\C sharp Course\Working_with_Files\Working_with_Files_1\Text.txt”;
列表=新列表();
var content=File.ReadAllText(路径);
var text=content.Trim();
字符串[]已拆分;
//分线
for(int i=0;i
对于文本文件中的每个字母,您将添加所有单词。您不需要for循环。您也不需要第二个循环,因为String.Split
有一个重载:
char[] splitChars = {',', ' ', '.', '(', ')'};
string[] splitted = text.Split(splitChars, StringSplitOptions.RemoveEmptyEntries);
获取重复次数最多的三个单词的子任务:
string[] top3RepeatingWords = splitted
.Groupby(w => w)
.OrderByDescending(g => g.Count())
.Select(g => g.Key)
.Take(3)
.ToArray();
对于文本文件中的每个字母,您将添加所有单词。您不需要for循环。您也不需要第二个循环,因为
String.Split
有一个重载:
char[] splitChars = {',', ' ', '.', '(', ')'};
string[] splitted = text.Split(splitChars, StringSplitOptions.RemoveEmptyEntries);
获取重复次数最多的三个单词的子任务:
string[] top3RepeatingWords = splitted
.Groupby(w => w)
.OrderByDescending(g => g.Count())
.Select(g => g.Key)
.Take(3)
.ToArray();
您的循环似乎没有意义,因为每个循环都会执行相同的操作:
for (int i = 0; i < text.Length; i++)//You do not use this i!
{
splitted = text.Split(',', ' ', '.', '(', ')');
list.Add(splitted);//Will add the same splitted text each time.
}
您的循环似乎没有意义,因为每个循环都会执行相同的操作:
for (int i = 0; i < text.Length; i++)//You do not use this i!
{
splitted = text.Split(',', ' ', '.', '(', ')');
list.Add(splitted);//Will add the same splitted text each time.
}
列表可能重复。添加(拆分)
没有意义splitted
是一个数组list.Add()
需要一个字符串。也许你想要AddRange()
,但是即使这样,如果你已经有了数组,为什么还要麻烦列表呢?可能重复list.Add(拆分)
splitted
是一个数组list.Add()
需要一个字符串。也许你想要AddRange()
,但即使如此,如果你已经有了数组,为什么还要麻烦列表呢?当我尝试添加StringSplitOptions时,它会说:无法转换为charah nevermind我没有看到你声明为Char,这有助于我更好地理解我的代码,非常感谢当我尝试添加StringSplitOptions时,它说:无法转换为charah nevermind我没有看到u声明为Char,这有助于我更好地理解我的代码,非常感谢