The function WordCount returns the variable "words" so the calling function can get its value. When a function returns a value you can use its function call like you would use a literal of the same type as the return type.
So if you had this string...
|
string myString = "Hello world";
|
The code...
|
cout << " The string has " << WordCount( myString ) << " words " << endl;
|
is essentially the same as...
|
cout << " The string has " << 2 << " words " << endl;
|
Because when this line of code is executed, before anything is printed to the screen, the function WordCount is executed and the integer "words" is returned to cout in the calling function (which, in the case of the string "myString" will be 2).
For this line of code...
|
if (Sentence[size] == ' ' && Sentence[size-1] != ' ')
|
I believe it's so if a string had two or more spaces between words, it wouldn't count as extra words.
So say you have the string...
|
string myString = "Hello World"; //two spaces!
|
With the original if statement...
|
if (Sentence[size] == ' '/*space*/)
|
It would get to the first space, increment words by one, then on the next iteration of the loop get to the second space and increment words again. So the value returned by WordCount would be 3, not 2..
but with this if statement...
|
if (Sentence[size] == ' ' && Sentence[size-1] != ' ')
|
It's only going to count the space with a non-space character to its immediate left.
So even if you had a string like this...
|
string myString = "Hello world";
|
with 10 space between words, the if statement will only execute for the first space, because the rest don't have non-space characters to their left.