简体   繁体   中英

Count All Character Occurrences in a String C#

What is the best way to dynamically count each character occurrence in C#?

given

string sample = "Foe Doe";

it should output something like

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

counting a single character would be easy but in my exam this was a bit tricky, I could only imagine a solution to get all unique characters -> then store it in a collection(preferably an array) then a nested for loop for the array and the string.

Is there a better solution than this?

使用 LINQ

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

You could use a Lookup<k,e> which is similar to a dictionary:

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

You can use Linq for that:

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

And tweaking you can remove empty characters, make case insensitive, etc..

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

And so on..

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

    }
}

Since string implements IEnumerable<char> , you can use the Linq .Where() and .GroupBy() extensions to count the letters and eliminate the whitespace.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM