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

In this example program, the frequency of occurrence of a character is checked for a C-style string.

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

Iterate over the given string S and increment the frequency of each character encountered by 1.

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, that is, \0 (ASCII value of null character is 0).
 How to define a C-string?
char str[] = "C++";
In the above code, str is a string and it holds 4 characters.
Although "C++" has 3 characters, the null character \0 is added to the end of the string automatically.

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 set the character variable check to s. declare an integer type variable int count with value 0.
 a for loop is iterated throughout the string until the end.  loop is iterated until the null character '\0' is encountered. The null character indicates the end of the string.
In each iteration, the occurrence of the character is checked. If found then the value of variable count which is already set to 0 is incremented by 1.
for(int i = 0; c[i] != '\0'; ++i)
   {
       if(check == c[i])
           ++count;
   }

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