Q:

Write a C++ program to count all the words in a given string

0

Write a C++ program to count all the words in a given string

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

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

#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;
}

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now