Using
The Standard C++ Library can significantly simplify your task.
I will assume that the words are white space separated, here is a demo application with
two different implementations of
WordCount
, both using the standard library utilities:
#include <iostream>
#include <sstream>
#include <string>
#include <iterator>
int WordCount1(const std::string& str)
{
int count = 0;
std::istringstream iss(str);
for(std::string word; iss >> word; ++count);
return count;
}
int WordCount2(const std::string& str)
{
std::istringstream iss(str);
return std::distance(std::istream_iterator<std::string>(iss),
std::istream_iterator<std::string>());
}
int main()
{
std::string str = "This\tis a test!\nI repeat, this is a test!";
std::cout << "\nWordCount1: " << WordCount1(str) << " words"
<< "\nWordCount2: " << WordCount2(str) << " words";
return 0;
}
The program output is:
WordCount1: 10 words
WordCount2: 10 words
You can see the simplicity here... Especially in second alternative which is just 2 lines of code.
Also note that tab (
'\t') and new line (
'\n') characters are also correctly interpreted.
If you want to understand how these algorithms work check out the documentation for
std::istream::operator>>[
^] and
std::distance[
^].
If the documentation is not clear enough for you, you are always welcome to share your concerns here. :)
Best Regards,
Nuri