Answer to Question #5787 in C++ for Kewal

Question #5787
Write a function which will take a string and returns the word count. Each word is separated by a single space.
1
Expert's answer
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!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS