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.
using namespace std;
int CountSpaces( char * str )
for ( int i = 0; str[i] != '\0'; i++)
if ( str[i] == ' ' )
noOfSpaces = noOfSpaces + 1;
char str = " Saad Bin Saulat ";
cout << "Number of spaces in string : " << CountSpaces( str ) << endl;
Number of spaces in string : 4