【问题标题】:Count how often a word appears in a string [duplicate]计算一个单词在字符串中出现的频率[重复]
【发布时间】:2018-10-22 01:48:31
【问题描述】:

假设我有这个字符串:

string common = "Blue;Red;Red;Green;Green;Green;Blue;Blue;Blue;Yellow";

现在我想数一下,这些词在这个字符串中出现的频率。

我不知道字符串会是什么样子。每次都不一样。

我希望字符串中的每个单词都有一个变量,其中包含该单词在字符串中出现的频率。

所以我应该得到类似的东西:

Blue: 4
Red: 2
Green: 3
Yellow: 1

【问题讨论】:

标签: c# string


【解决方案1】:
string common = "Blue;Red;Red;Green;Green;Green;Blue;Blue;Blue;Yellow";
var grouped = common.Split(';')
    .GroupBy(x => x)
    .Select(x => new {
        x.Key,
        Count = x.Count(),
    });

foreach(var grouping in grouped)
{
    Console.WriteLine($"{grouping.Key}: {grouping.Count}");
}

输出:

Blue: 4
Red: 2
Green: 3
Yellow: 1

或者(每 cmets 大约 ToDictionary),这可以工作:

var grouped = common.Split(';')
    .GroupBy(x => x)
    .ToDictionary(x => x.Key, x => x.Count());

并在显示循环中,将{grouping.Count} 更改为{grouping.Value}

【讨论】:

  • 甚至不需要grouped 变量。或投影到匿名对象
  • ToDictionary(x => x.Key, x => x.Count()) 而不是Select 以获得一个不错的字典来进行查找。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-29
  • 2019-07-31
  • 2013-12-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多