Home > Net >  Find and Count works but not the way I want
Find and Count works but not the way I want

Time:12-22

        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 :

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

CodePudding user response:

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'

CodePudding user response:

Klaus' answer might be easier to understand, but you can also use this function which does mostly the same thing:

public static int CountDuplicates(string str) =>
    (from c in str.ToLower()
    group c by c
    into grp
    where grp.Count() > 1
    select grp.Key).Count();

Usage: var dupes = $"{word} - Duplicates: {CountDuplicates(word)}";

  • Related