计算字符串中所有字符的出现次数

本文关键字:字符 字符串 计算 | 更新日期: 2023-09-27 18:06:53

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

给定

string sample = "Foe Doe";

它应该输出类似

的内容
f = 1
o = 2
e = 2
d = 1

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

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

计算字符串中所有字符的出现次数

使用LINQ

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

您可以使用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()}")

您可以使用类似于字典的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());
  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();     
    }
}

由于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));
}
          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();
      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}");
        }
        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();
    }