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

  • برمجة سي بلس بلس
  • برمجة

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

 

الأجوبة

#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;
}
هل كان المحتوى مفيد؟

تبحث عن مدرس اونلاين؟

محتاج مساعدة باختيار المدرس الافضل؟ تواصل مع فريقنا الان لمساعدتك بتأمين افضل مدرس
ماهو التخصص الذي تبحث عنه؟
اكتب هنا...