+92 332 4229 857 99ProjectIdeas@Gmail.com

How to count total number of spaces in a string (C++)


Counting spaces in a string
CountSpaces() takes a character array (string) as an input parameter and returns the total number of spaces in the input string.
Summary of CountSpaces()
This function uses a variable named noOfSpaces to store the total number of spaces in a string and is initialized by 0. A for loop starts from the 0th index of the string and iterates till end. The end of the string is indicated by the NULL character ‘\0’ which is present at the end of every string. At each iteration of the for loop, the character is checked – if the character is a space then the noOfSpaces variable is increamented by one and after the loop is terminated - the value of noOfSpaces variable is returned from the function.

Code

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

using namespace std;

int CountSpaces( char * str )
{
       int noOfSpaces=0;
       for ( int i = 0; str[i] != '\0'; i++)
       {
              if ( str[i] == ' ' )
              {
                     noOfSpaces = noOfSpaces + 1;
              }
       }
       return noOfSpaces;
}

int main()
{
       char str[] = " Saad Bin Saulat ";
       cout <<  "Number of spaces in string : " << CountSpaces( str ) << endl;
      
       _getche();
       return 0;
}

Output
Number of spaces in string : 4

0 comments: