For a given string in C# count the number of occurrences of each >character that repeats itself (occurs more than once).
Example:
string str = "abcdzefazz";
Expected output:
Character a has 2 occurrences.
Character z has 3 occurrences.
For a given string in C# count the number of occurrences of each >character that repeats itself (occurs more than once).
Example:
string str = "abcdzefazz";
Expected output:
Character a has 2 occurrences.
Character z has 3 occurrences.
Well, for No Linq solution you can use good old foreach
loop with a help of dictionary Dictionary<char, int>
. Here Key
is character itself and Value
is occurence:
string str = "abcdzefazz";
...
Dictionary<char, int> occurence = new Dictionary<char, int>();
foreach (char c in str)
if (occurence.TryGetValue(c, out value))
occurence[c] = value + 1;
else
occurence.Add(c, 1);
When you want to know occurence (number
) of ch
character:
char ch = 'z';
...
int number = occurence.TryGetValue(ch, out value) ? value : 0;
To print all occurence
, just loop over the dictionary:
foreach (var pair in occurence)
Console.WriteLine($"Character {pair.Key} has {pair.Value} occurrences");
To obtain all characters with more then 1 ocurrence, just add condition:
foreach (var pair in occurence)
if (pair.Value > 1)
Console.WriteLine($"Character {pair.Key} has {pair.Value} occurrences");