String Programming, String Function, String in C++
Write a C++ program to count number of words in string.


#include<iostream>
using namespace std;
int main( )
{
int i;
int words = 0; // Variable to holds number of words
char name[30];
cout << "Enter a string to count number of words in it: ";
cin.getline(name, 30);
for(i = 0; name[i] != '\0'; i++)
{
if (name[i] == ' ') //  to Check for spaces
{
words = words + 1;
}
}
cout << "Total number of words in string is = " ;
cout<< words+1 
cout<< endl;
return 0;
}


Program output is tested on www.jdoodle.com

Output:
Enter a string to count number of words in it: Mukesh Rajput  

Total number of words in string is = 2


Thanks
Mukesh Rajput

Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: