C++ Program to find the frequency of characters in a c-style string


January 21, 2023, Learn eTutorial
1188

What is a string in C++?

A string can be defined as a sequence of characters to form a word.

How to find the frequency of occurrence of a character in a string?

For finding the frequency of a character in a string, we have to traverse through the string and increment a counter if we reach the specified character.

C-strings in C++
 

In C programming, the collection of characters is stored in the form of arrays. This is also supported in C++ programming. Hence it's called C-strings. C-strings are arrays of type char terminated with a null character, 

C++ program to find the frequency of characters of a C-style string

Here a character type array is created c[ ] and pass the string “learnetutorials is very useful” and ask the user to add a character that wants to check and store it in a variable. declare an integer type variable int count with value 0. Now open a for loop throughout the string until the null character '\0' is encountered.

In each iteration, the occurrence of the character is checked. If found then the value of the variable count which is already set to 0 is incremented by 1. Finally, display the value of the count on the screen.

Algorithm

Step 1:  Call the header file iostream.

Step 2: Use the namespace std.

Step 3: Open the integer type main function; int main().

Step 4: Declare a character  type array c[ ]= “learnetutorials is very useful”;

Step 5: set the character to be checked to a character variable check

Step 6: Initialize the value of variable count to 0;

Step 7:Iterate through the string using a for loop until the last character.

Step 8: check for each character if it is equal to check;

Step 9:Increment the value of count by 1 if yes.

Step 10: display the value of the count

Step 11: exit;
 

C++ Source Code

                                          #include <iostream>

using namespace std;
int main()
{
   char c[] = "learnetutorials is very useful.", check = 's';
   int count = 0;

   for(int i = 0; c[i] != '\0'; ++i)
   {
       if(check == c[i])
           ++count;
   }
   cout << "Frequency of " << check <<  " = " << count;
   return 0;
}
                                      

OUTPUT

Frequency of s = 3