Answer to Question #5787 in C++ for Kewal
Write a function which will take a string and returns the word count. Each word is separated by a single space.
1
2011-12-29T08:08:44-0500
C++:
Write a function which will take a string and returns the word count. Each word is separated by a single space.
#include <cctype>
int CountWords(const char* str)
{
if (str == NULL)
cout<<"Error: empty string";
bool inSpaces = true;
int numWords = 0;
while (*str != NULL)
{
if (std::isspace(*str))
{
inSpaces = true;
}
else if (inSpaces)
{
numWords++;
inSpaces = false;
}
++str;
}
return numWords;
}
Need a fast expert's response?
Submit order
and get a quick answer at the best price
for any assignment or question with DETAILED EXPLANATIONS!
Learn more about our help with Assignments:
C++
Comments
Leave a comment