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

时间:2016-09-13 14:24:01

标签: c# string count character

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

给定的

string sample = "Foe Doe";

它应输出类似

的内容
f = 1
o = 2
e = 2
d = 1
计算单个角色很容易,但在我的考试中这有点棘手,我只能想象一个获得所有独特角色的解决方案 - >然后将它存储在一个集合(最好是一个数组)中,然后将它存储在数组和字符串的嵌套for循环中。

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

8 个答案:

答案 0 :(得分:7)

使用LINQ

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

答案 1 :(得分: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());

答案 2 :(得分:1)

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

等等..

答案 3 :(得分:0)

  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();     

    }
}

答案 4 :(得分:0)

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

答案 5 :(得分:0)

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

        }

答案 6 :(得分:-1)

          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 :(得分:-1)

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