Get max occurred character in string in c#

Most of the time in interview (fresher or 1 year) interviewer asks this questing and says that not to use inbuilt function use only basic function and find maximum occurring character for a string entered as well as find the no of occurrence of that character.

Following code find the maximum occurring character in the given string it takes string as a input and returns maximum occurred character as char of that string.

WAP For Maximum Occurred Char - Code C#



public char MostOccurringCharInString(string charString)
{
    int mostOccurrence = -1;
    char mostOccurringChar = ' ';
    foreach (char currentChar  in charString)
    {
        int foundCharOccreence = 0;
        foreach (char charToBeMatch in charString)
        {
            if (currentChar == charToBeMatch)
                foundCharOccreence++;
        }
        if (mostOccurrence < foundCharOccreence)
        {
            mostOccurrence = foundCharOccreence;
            mostOccurringChar = currentChar;
        }
    }
    return mostOccurringChar;
}

Only need to calculate max occurrence of max occurred character.

Following code find the occurrence of the maximum occurred character in the given string it takes string as a input and returns occurrence of maximum occurred character as int of that string.

WAP For Occurrence of the Maximum Occurred Char - Code C#



public int MostOccurrenceOfCharInString(string charString)
{
    int mostOccurrence = -1;
    char mostOccurringChar = ' ';
    foreach (char currentChar  in charString)
    {
        int foundCharOccreence = 0;
        foreach (char charToBeMatch in charString)
        {
            if (currentChar == charToBeMatch)
                foundCharOccreence++;
        }
        if (mostOccurrence < foundCharOccreence)
        {
            mostOccurrence = foundCharOccreence;
            mostOccurringChar = currentChar;
        }
    }
    return mostOccurrence;
}


Recent Article