Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Return maximum occurring character in the input string in C++?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 6.6k
    Comment on it
    // C++ program to output the maximum occurring character in a string
    
    #include<bits/stdc++.h>
    #define ASCII_SIZE 256
    using namespace std;
     
    char getMaxOccuringChar(char* str)
    {
        int count[ASCII_SIZE] = {0};//create an array to keep character count and initialize it to 0
        
        int len = strlen(str);   //length of string
    
        for (int i=0; i<len; i++)  //loop for character count
            count[str[i]]++;
     
        int max = -1;  // Initialize max count
    
        char result;   // Initialize result
     
        for (int i = 0; i < len; i++) 
       {
            if (max < count[str[i]])  //comparing a maximum count with each character count
            {
                max = count[str[i]]; //assign character count to max value if condition is true
                result = str[i];    //assign maximum character count character to result
            }
        }
     
        return result;
    }
     
    int main()
    {
        char str[] = "sample string";
        cout << "Max occurring character is " << getMaxOccuringChar(str);
    }

    Output:

    Max occurring character is s

    Explanation:

    In the above program, a function getMaxOccuringChar() is defined in which a string is passed, an array count of size 256 is defined as there are 255 characters. The logic behind above program is evaluating length of passed string and running a for loop till string length, within for loop count array is incremented for each character in the string hence providing character count for each character. Finally, a max value is initialized to -1 and compared with each character count to get maximum character count within string. Maximum character count character is stored in result variable and is returned from function.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: