C++ Exercises: Count all the words in a given string
C++ String: Exercise-8 with Solution
Write a C++ program to count all the words in a given string.
Pictorial Presentation:
Sample Solution:
C++ Code :
#include <iostream>
#include <string>
using namespace std;
int Word_count(string text) {
int ctr = 0;
for (int x = 0; x < text.length(); x++)
{
if (text[x] == ' ')
ctr++;
}
return ctr + 1;
}
int main() {
cout << "Original string: Python, number of words -> " << Word_count("Python") << endl;
cout << "\nOriginal string: CPP Exercises, number of words -> " << Word_count("CPP Exercises") << endl;
cout << "\nOriginal string: After eagling the Road Hole on Thursday, he missed an 8-footer for birdie Friday., \nnumber of words -> ";
cout << Word_count("After eagling the Road Hole on Thursday, he missed an 8-footer for birdie Friday.") << endl;
return 0;
}
Sample Output:
Original string: Python, number of words -> 1 Original string: CPP Exercises, number of words -> 2 Original string: After eagling the Road Hole on Thursday, he missed an 8-footer for birdie Friday., number of words -> 14
Flowchart:
C++ Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a C++ program to count all the vowels in a given string.
Next: Write a C++ program to check whether two characters present equally in a given string.
What is the difficulty level of this exercise?