Calculate the number of words in an English sentence.

Source: Internet
Author: User

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;
}

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.