Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find and Count works but not the way I want

        byte count = 0;
        string word = "muumuu";
        string res= word;
        bool flg = true;
        foreach(char ch in word)
        {
            res = res.Remove(0,1);
            if(res.Contains(ch))
            {
                flg = false;
                count ++;
                Console.WriteLine($"there are {count} same chars : {ch}");
            }
        }
        if(flg)
        {
            Console.WriteLine($"All chars are different in : {word} ");
        }

The output is :

there are 1 same chars : m
there are 2 same chars : u
there are 3 same chars : u
there are 4 same chars : u

The question is how to count same chars like :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

there are 2 same chars : m
there are 4 same chars : u

>Solution :

You have to separate the counting from the output of the result.

The following solution collects the character counts in a dictionary and after that displays the contents of the dictionary:

string word = "muumuu";

var counts = new Dictionary<char, int>();
foreach (var ch in word)
{
    if (counts.ContainsKey(ch))
        counts[ch]++;
    else
        counts[ch] = 1;
}

foreach (var chCount in counts)
{
   Console.WriteLine($"{chCount.Value} occurrences of '{chCount.Key}'");
}

A very compact alternative solution using Linq GroupBy method:

string word = "muumuu";

foreach (var group in word.GroupBy(c => c))
{
   Console.WriteLine($"{group.Count()} occurrences of '{group.Key}'");
}

GroupBy groups the characters in the word so that each distinct character creates a group and each group contains the collected identical characaters. These can then be counted using Count.

Result:

2 occurrences of 'm' 
4 occurrences of 'u'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading