【问题标题】:Count All Character Occurrences in a String C#计算字符串 C# 中的所有字符出现次数
【发布时间】:2016-09-13 14:24:00
【问题描述】:

在 C# 中动态计算每个字符出现次数的最佳方法是什么?

给定

string sample = "Foe Doe";

它应该输出类似的东西

f = 1
o = 2
e = 2
d = 1

计算单个字符会很容易,但在我的考试中这有点棘手,我只能想象一个获取所有唯一字符的解决方案 -> 然后将其存储在一个集合中(最好是一个数组),然后是一个嵌套的 for 循环数组和字符串。

还有比这更好的解决方案吗?

【问题讨论】:

  • 使用Dictionary<char, int> 来跟踪每个字符的计数。
  • 每个字符表示每个字母?
  • 定义“最佳”:最快?最容易理解?最容易编码? “最聪明”?
  • 还需要考虑大小写吗?您的示例似乎表明您需要不区分大小写的方法。
  • @juharr Gosh 我怎么没想到呢!

标签: c# string count character


【解决方案1】:

使用 LINQ

sample.GroupBy(c => c).Select(c => new { Char = c.Key, Count = c.Count()});

【讨论】:

  • 再澄清一点,这利用了stringchars 的集合这一事实,所以GroupBy 会很高兴地对其进行迭代。
【解决方案2】:

您可以使用类似于字典的Lookup<k,e>

var charLookup = sample.Where(char.IsLetterOrDigit).ToLookup(c => c); // IsLetterOrDigit to exclude the space

foreach (var c in charLookup)
    Console.WriteLine("Char:{0} Count:{1}", c.Key, charLookup[c.Key].Count());

【讨论】:

    【解决方案3】:

    您可以为此使用 Linq:

    sample.GroupBy(x => x).Select(x => $"{x.Key} = {x.Count()}").
    

    您可以通过调整删除空字符、不区分大小写等。

    str.ToLower().GroupBy(x => x).Where(x => x.Key != ' ').Select(x => $"{x.Key} = {x.Count()}")
    

    等等..

    【讨论】:

    • @KonstantinErshov 打败了我:p
    • 与其通过调用.ToLower 来创建新的string,不如将​​Char.ToLower 作为GroupBy 表达式并利用Char.IsWhiteSpace 来检查空格,而不仅仅是常规空格。
    • 很好,我不习惯字符串/字符验证/转换原生函数。我会把这些添加到我的日常生活中!
    【解决方案4】:
      class Program
    {
        static void Main(string[] args)
        {
            const string inputstring = "Hello World";
            var count = 0;
    
            var charGroups = (from s in inputstring
                              group s by s into g
                              select new
                              {
                                  c = g.Key,
                                  count = g.Count(),
                              }).OrderBy(c => c.count);
            foreach (var x in charGroups)
            {
                Console.WriteLine(x.c + ": " + x.count);
                count = x.count;
            }
    
            Console.Read();     
    
        }
    }
    

    【讨论】:

      【解决方案5】:

      由于string 实现了IEnumerable<char>,您可以使用Linq .Where() 和.GroupBy() 扩展来计算字母并消除空格。

      string sample = "Foe Doe";
      
      var letterCounter = sample.Where(char.IsLetterOrDigit)
                                .GroupBy(char.ToLower)
                                .Select(counter => new { Letter = counter.Key, Counter = counter.Count() });
      
      foreach (var counter in letterCounter)
      {
          Console.WriteLine(String.Format("{0} = {1}", counter.Letter, counter.Counter));
      }
      

      【讨论】:

        【解决方案6】:
                  string str;
                  int i, cnt;
                Console.WriteLine("Enter a sentence");
                str = Console.ReadLine();
                char ch;
                for (ch = (char)65; ch <= 90; ch++)
                {
                    cnt = 0;
                    for ( i = 0; i < str.Length; i++)
                    {
        
                        if (ch == str[i] || (ch + 32) == str[i])
                        {
                            cnt++;
                        }
                    }
                    if (cnt > 0)
                    {
                        Console.WriteLine(ch + "=" + cnt);
                    }
                }
        
        
                Console.ReadLine();
        

        【讨论】:

          【解决方案7】:
                string str = "Orasscleee";
                  Dictionary<char,int> c=new Dictionary<char, int>();
                  foreach (var cc in str)
                  {
                      char c1 = char.ToUpper(cc);
                      try
                      {
                          c.Add(c1,1);
                      }
                      catch (Exception e)
                      {
                          c[c1] = c[c1] + 1;
                      }
                  }
                  foreach (var c1 in c)
                  {
                      Console.WriteLine($"{c1.Key}:{c1.Value}");
          
                  }
          

          【讨论】:

          • 你没有得到哪一部分?
          【解决方案8】:
                  string new_string= String.Concat(s.OrderBy(c => c)); //for sorting string
                  for (int i = 0; i < new_string.Length; i++)
                  {
                      int count = 0;
                      for (int j = i; j < new_string.Length; j++)
                      {
          
                          if (new_string[i] == new_string[j])
                          {
                              count++;
                          }
                          else
                          {
                              if (count == 0)
                              { count = 1; }
                              break;
                          }
          
                      }
                      Console.WriteLine("count for "+new_string[i]+"is: "+count);
                      new_string=new_string.Remove(0, count);
                      i = 0;
                  }
                  Console.ReadKey();
              }
          

          【讨论】:

          • 您好,欢迎来到 SO,您能否简要解释一下您的回答如何帮助 OP 的问题?
          猜你喜欢
          • 2023-02-04
          • 2014-07-03
          • 2015-12-01
          • 2011-04-21
          • 1970-01-01
          • 2014-04-24
          • 2011-12-16
          • 1970-01-01
          相关资源
          最近更新 更多