+92 332 4229 857 99ProjectIdeas@Gmail.com

How to count a specific character in a string (C++ Tutorial)


Counting specific character in a string
CountCharacter() takes two arguments as its input parameter; first is the string and the second is the character to count.
Code of CountCharacter()

int CountCharacter( char * str , char ch )
{
       int countChar = 0;

       for ( int i = 0; str[i] != '\0'; i++)
       {
               if ( str[i] == ch )
                     countChar = countChar + 1;
       }

       return countChar;
}
Summary of CountCharacter()
First a variable countChar is declared and initialized as 0.
After that a for loop starts from the 0th index of the string and iterates till end.End of the string is indicated by '\0'.At each iteration the current character is compared with the character to count.
   if ( str[i] == ch )
If the current character of the string is equal to the character to count, then it increaments the countChar variable:
   countChar = countChar + 1;
At the end of the for loop, the value of the countChar variable is returned from the function – which gives the count of the specific character.

Code

#include "stdafx.h"
#include "iostream.h"
#include "conio.h"

using namespace std;

int CountCharacter( char * str , char ch )
{
       int countChar = 0;
      
      for ( int i = 0; str[i] != '\0'; i++)
       {
               if ( str[i] == ch )
                     countChar = countChar + 1;
       }

       return countChar;
}

int main()
{
      char str[] = "saad bin saulat";

cout << "s comes : " << CountCharacter( str , 's' ) << " times" << endl;
      cout << "a comes : " << CountCharacter( str , 'a' ) << " times" << endl;
      cout << "d comes : " << CountCharacter( str , 'd' ) << " times" << endl;
      cout << "b comes : " << CountCharacter( str , 'b' ) << " times" << endl;
      cout << "i comes : " << CountCharacter( str , 'i' ) << " times" << endl;
      cout << "n comes : " << CountCharacter( str , 'n' ) << " times" << endl;
      cout << "u comes : " << CountCharacter( str , 'u' ) << " times" << endl;
      cout << "l comes : " << CountCharacter( str , 'l' ) << " times" << endl;
      cout << "t comes : " << CountCharacter( str , 't' ) << " times" << endl;
       
       _getche();
       return 0;
}

Output
s comes : 2 times
a comes : 4 times
d comes : 1 times
b comes : 1 times
i comes : 1 times
n comes : 1 times
u comes : 1 times
l comes : 1 times
t comes : 1 times

0 comments: