Given an English sentence, besides letters, it also contains space carriage return and horizontal tabulation symbols ('\ t',' \ n '), calculate the number of words in an English sentence based on these three symbols.
The method shown below is what I saw from a foreign website. The idea is clear and logical, so I decided to record it:
Set two flags: IN, OUT, and a variable state. When a letter is encountered, the state value is IN, and when the three characters mentioned above are met, the state is OUT. You can test any situation, including two words with multiple spaces in the middle. The following code is provided:
[Cpp]
# Include <iostream>
# Include <string>
Using namespace std;
Unsigned int count_word (char * s ){
Const int OUT = 0;
Const int IN = 1;
Int state = OUT;
Unsigned int count = 0;
While (* s ){
If (* s = ''| * s = '\ T' | * s =' \ n ')
State = OUT;
Else if (OUT = state ){
State = IN;
++ Count;
}
S ++;
}
Return count;
}
Int main (int argc, char * argv []) {
Char s [] = "this is a test \ n this is a test ";
Cout <count_word (s) <endl;
Cin. get ();
Return 0;
}
# Include <iostream>
# Include <string>
Using namespace std;
Unsigned int count_word (char * s ){
Const int OUT = 0;
Const int IN = 1;
Int state = OUT;
Unsigned int count = 0;
While (* s ){
If (* s = ''| * s = '\ T' | * s =' \ n ')
State = OUT;
Else if (OUT = state ){
State = IN;
++ Count;
}
S ++;
}
Return count;
}
Int main (int argc, char * argv []) {
Char s [] = "this is a test \ n this is a test ";
Cout <count_word (s) <endl;
Cin. get ();
Return 0;
}