Can someone explain these lines for me

Hi I was searching for a word count code and I came across this one
http://www.cplusplus.com/forum/beginner/1404/
witch I think is the easiest one to understand.

Except these lines that I can't seem to understand

cout << " The string has " << WordCount(Mystring) << " words " << endl

if (Sentence[size] == ' ' && Sentence[size-1] != ' ')

and return word;

so my questions are :
Why does it count multiple spaces as one
Why return word and how does the program know in the WordCount(Mystring) know the count since it hasn't been declared above that how to count it

don't need some major thesis for this :P

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.


Last edited on
Thx alot man, just what I needed to know :D
Topic archived. No new replies allowed.