计算数组中字符串的出现次数

Ebi*_*ser 0 c# arrays string count

我正在计算阵列中存在多少个字符串 -

Tags = "the cat the mat the sat";

string[] words = Tags.Split(' ');

int counter = 0;

foreach (string item in words)
{
    if (item != "")
    {
      counter++;

    }
}
Run Code Online (Sandbox Code Playgroud)

但是,我怎么能修改我的代码,以便计算每个字符串的出现次数.所以例如 -

  • "the"= 3
  • "猫"= 1
  • "mat"= 1
  • "sat"= 1

然后以某种方式存储这些值?

giZ*_*Zm0 7

您没有说出您使用的是哪种语言,但我认为它看起来像c#.这是一种方法.

    Dictionary<string, int> dictionary = new Dictionary<string, int>();
    foreach (string word in words)
    {
        if (dictionary.ContainsKey(word))
        {
            dictionary[word] += 1; 
        }
        else
        {
            dictionary.Add(word,1);
        }
    }
Run Code Online (Sandbox Code Playgroud)


dtb*_*dtb 6

试试这个:

var result = tags.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                 .GroupBy(tag => tag)
                 .ToDictionary(group => group.Key, group => group.Count());
Run Code Online (Sandbox Code Playgroud)
var max = result.MaxBy(kvp => kvp.Value);
var min = result.MinBy(kvp => kvp.Value);
Run Code Online (Sandbox Code Playgroud)

使用MoreLINQ的MaxBy和MinBy.