C++ Program to Find the Frequency of Characters in a String

C++ program to print count of all alphabets in a string.


C++ program to print frequency of characters in a string

#include <iostream>
#include <cstring>

using namespace std;
 
int main(){
    char inputString[1000];
    // we are using an integer array(initialized with zero) to store 
    // frequency of characters at index equal to their ascii value
    int i, count[256] = {0};
    
    cout << "Enter a String\n";
    gets(inputString);
    
    for(i=0; inputString[i] != '\0'; i++){
        // Populate frequency count array
        count[inputString[i]]++;
    }
    
    cout << "\nCharacter   Frequency\n";
    for(i=0; i < 256; i++){
        if(count[i] != 0){
          cout <<"  " << (char)i << "         " 
              << count[i]<< endl;                    
        }
    }
 
    return 0;
}
Output
Enter a String
abbcd

Character   Frequency
   a        1
   b        2
   c        1
   d        1

Recommended Posts
C++ Program to Count Number of Vowels, Consonant, and Spaces in String
C++ Program to find length of string
C++ Program to concatenate two strings without using strcat function.
C++ Program to Copy String Without Using strcpy
C++ Program to Find Smallest Element in Array
C++ Program to Find Largest Element of an Array
C++ Program to Check Whether a Character is Vowel or Consonant
C++ Program to Delete Spaces from String or Sentence
C++ Program to Delete a Word from Sentence
All C++ Programs