忽略区分大小写

本文关键字:大小写 略区 | 更新日期: 2023-09-27 18:20:32

我必须计算给定输入文本中的每个单词在其中出现的次数。我陷入困境的地方是:应该忽略字符大小写的差异。

例如:"You are here.You You"->输出:

are=1
here=1
You=3

我所做的:

string text = "You are here.You you";
IDictionary<string, int> wordsCount = new SortedDictionary<string, int>();
string[] words = text.Split(' ',',','.','-','!');
foreach (string word in words)
{
    int count = 1;
    if (wordsCount.ContainsKey(word))
        count = wordsCount[word] + 1;
    wordsCount[word] = count;
}
var items = from pair in wordsCount
            orderby pair.Value ascending
            select pair;
foreach (var p in items)
{
    Console.WriteLine("{0} -> {1}", p.Key, p.Value);
}

是否有机会在不手动检查给定文本中的每个单词的情况下实现这一点?例如,如果我有一个很长的段落,不使用特定的方法检查每个单词?

忽略区分大小写

只需添加

for(i = 0; text[i] != ''0'; i++){
    text[i] = text[i].ToLower();
}

但由于text是一个字符串,只需执行:

text = text.ToLower();

就在string[] words = text.Split(' ',',','.','-','!');行之前。然后尽情享受吧!

linq怎么样?

var text = "You are here.You you";
var words = text.Split(' ', ',', '.', '-', '!');
words
    .GroupBy(word => word.ToLowerInvariant())
    .OrderByDescending(group => group.Count())
    .ToList()
    .ForEach(g=> Console.WriteLine(g.Key + "=" + g.Count()));