count number of spaces in a given sentence – CSKC
Sign In

Search

Solved Problem #CPP#2614    siteicon   siteicon  

Problem Statement - count number of spaces in a given sentence

Write a program  to count the number of space characters in a given input string or sentence using the character match for space character ‘ ‘.

Solution

TC++ #2614

 

×

Ask AI About This Code

Default Prompt that is passed along with the code is given below, You can write your own prompt if you so desire.



×

Test CPP

  Related ( ? ) :

char str[80]; //Character array for string storage.
int sp_count=0; //variable for initialisation of space count

cout<<“Input a small sentence:” ; cin.getline(str,80);
Collecting the user input in given character array and putting the null character automatically.

for(int i=0;str[i]!=”;i++) //The loop runs till null character is found
{
if(str[i]==’ ‘) sp_count++; //The sp_count is increased the moment match of character at given position while iteration is equal to space character. single space character is given in single quotes with one space in between.
}
cout<<“Number of spaces in given input =”<<sp_count<<endl;
Output is printed.

Notes

  • Using this technique any specific character or a range of characters can be found.
  • The logic of using isspace() check can also be used if we need to count all kinds of white spaces lie space, tab etc.
  • For loop traversing check with length returned from strlen() function can also be used.

Common Errors

  • Do not forget to initialise int sp_count=0;


Share

Created: 13-Jan-2018 21:32 | Updated: 29-Nov-2018 17:27|