Home > database >  count the occurrence of letters in a string and output the letter with the highest occurrence
count the occurrence of letters in a string and output the letter with the highest occurrence

Time:11-12

I want to count the occurence of each letter in a string and afterwards find out the letter with the highes occurrence and then return it as a char to the main method. Im just a beginner in coding so I would appreciate simple answers and solutions without adding anything from the library. Thank you for your time, I appreciate it

What I have right now:

to count the occurrence for each letter (doesnt work):

int count = 0;
for (int i = 0; i < s.Length; i  ) 
{
    if (s[0] == s[i])
    {
        count  ;
    }
}

to find out the highest number in the array:

int max = s[0];
for (int i = 0; i < s.Length; i  )
{
    if (s[i] > max)
    {
        max = s[i];
     }
}

afterwards i want to return the value as a char and output the letter

CodePudding user response:

The problem with the existing code is there is only one count variable, but there are many different letters in the string. You need a way to keep a separate count for each different letter you encounter. A Dictionary<char,int> might be a good start, or an int[] with 26 items (one for each letter in order) could do the job. There are other structures that can work, too.

Beyond that, this looks like a learning problem, where you would not be well-served by seeing more code, but rather will do better to puzzle out the rest on your own.

CodePudding user response:

You can query string with a help of Linq:

using System.Linq;

var result = s
  .GroupBy(c => c)
  .MaxBy(g => g.Count())
  .Key;

No Linq solution can use Dictionary<char, int> where Key is character and Value is its frequency.

var freq = new Dictionary<char, int>();

foreach (char c in s)
  if (freq.TryGetValue(c, out int count))
    freq[c] = count   1;
  else
    freq.Add(c, 1);

int maxCount = 0;
char result = '\0';

foreach (var pair in freq)
  if (pair.Value > maxCount) {
    maxCount = pair.Value;
    result = pair.Key; 
  }
  • Related