2013年8月17日 星期六

494 - Kindergarten Counting Game

Everybody sit down in a circle. Ok. Listen to me carefully.
``Woooooo, you scwewy wabbit!''
Now, could someone tell me how many words I just said?

Input and Output

Input to your program will consist of a series of lines, each line containing multiple words (at least one). A ``word'' is defined as a consecutive sequence of letters (upper and/or lower case).

Your program should output a word count for each line of input. Each word count should be printed on a separate line.

Sample Input


Meep Meep!
I tot I taw a putty tat.
I did! I did! I did taw a putty tat.
Shsssssssssh ... I am hunting wabbits. Heh Heh Heh Heh ...

Sample Output


2
7
10
9

出處: http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=435



這題是要求您去數有幾個英文單字,這邊一個單字的定義是連續的大寫或小寫英文字母就算一個單字,所以只要搭配布林變數就可以解決此題。當遇到第一個英文字母的時候將布林設定為true並且單字數加一,當遇到不是英文字母的時候就將布林改為false,依此類推就可以數出有幾個英文單字。

c++ code:

#include <iostream>
using namespace std;

int main() {
    string line;

    while (getline(cin, line)) {
        bool flag = false;
        int count = 0;

        for (int i=0; i<line.length(); i++) {
            if ((line[i] >= 'A' && line[i] <= 'Z') || (line[i] >= 'a' && line[i] <= 'z')) {
                if (!flag) {
                    count++;
                    flag = true;
                }
            }
            else
                flag = false;
        }
        cout << count << endl;
    }

    return 0;
}

沒有留言:

張貼留言