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

C# 计算数组中字符串的出现次数,c#,arrays,string,count,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++; } } 但是,如何修改代码,以便计算每个字符串的出现次数。 比如说- “the”=3 “猫”=1 “垫”=1 “sat”=1

我正在计算数组中存在多少字符串-

Tags = "the cat the mat the sat";

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

int counter = 0;

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

    }
}
但是,如何修改代码,以便计算每个字符串的出现次数。 比如说-

  • “the”=3
  • “猫”=1
  • “垫”=1
  • “sat”=1

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

将这些值存储在一个地图中,其中键是单词,值是它出现多少次的计数器……

你没有说你使用什么语言,但我看到的是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);
        }
    }
Dictionary Dictionary=newdictionary();
foreach(单词中的字符串)
{
if(字典.ContainsKey(单词))
{
字典[字]+=1;
}
其他的
{
添加(单词,1);
}
}

您必须使用字典。这是:

        string Tags = "the cat the mat the sat";

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

        Dictionary<string, int> oddw = new Dictionary<string, int>();

        foreach (string item in words)
        {
            if (item != "")
            {
                if (oddw.ContainsKey(item) == false)
                {
                    oddw.Add(item, 1);
                }
                else
                {
                    oddw[item]++;
                }
            }
        }

        foreach (var item in oddw)
        {
            Console.WriteLine(item);
        }
string Tags=“猫垫sat”;
string[]words=Tags.Split(“”);
Dictionary oddw=新字典();
foreach(单词中的字符串项)
{
如果(项目!=“”)
{
如果(oddw.ContainsKey(项目)=false)
{
oddw.添加(第1项);
}
其他的
{
oddw[项目]+;
}
}
}
foreach(oddw中的var项目)
{
控制台写入线(项目);
}
试试这个:

var result = tags.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                 .GroupBy(tag => tag)
                 .ToDictionary(group => group.Key, group => group.Count());


是否仅使用MaxBy和MinBy from.

整词?例如,“there”应该与“the”匹配吗?这个问题可能也很有趣:我很抱歉,我刚刚意识到我接受了错误的答案。这是正确的答案。giZm0的答案同样正确,只是使用了不同的样式(与问题中的代码样式相匹配的样式)。既然你明确要求修改你的代码,我会认为GIZM0的答案比我的更正确,但是当然这取决于你哪一个答案最能解决你的问题:-好的,我又改变了!dtb我仍然使用了你的答案,因为它确实看起来更有效率。我很好奇如何使用您的技术计算出最大值和最小值?@dtb很好的解决方案。“一句话”总是很好。我感谢你们两位的帮助,你们建议使用@giZmo的答案是很诚实的。
var max = result.MaxBy(kvp => kvp.Value);
var min = result.MinBy(kvp => kvp.Value);