The Problem
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
解題思考
這一題的重點在於判斷字元是否是英文字母。
作法是先利用一個 boolean 變數,代表 "是否已讀到一個 Word"。只要碰到非英文字母,且此變數為真時,就代表在此之前的是符合題意的 "Word" ,因此將記錄的總字數遞增。
只要將這種解題思維釐清,這一題也就迎刃而解了。
參考解答(C++)
#include <iostream> #include <string> using namespace std; int main(void) { string get; while (getline(cin, get)) { int n = 0; bool word = false; for (int i = 0; i < get.size(); i++) { if ((get[i] >= 'a' && get[i] <= 'z') || (get[i] >= 'A' && get[i] <= 'Z')) { word = true; } else if (word) { word = false; n++; } } if (word) { n++; } cout << n << endl; } #ifndef ONLINE_JUDGE system("pause"); #endif return 0; }
2 回覆:
如果句尾也是英文字,而非標點符號
這份參考解答好像會少算1個的樣子
另外最近在研究字串樣是規則運算式(Ragex)
1行就解決了XD,感覺有點白目
http://kgame-blog.spaces.live.com/blog/cns!1A7962FEA74AB4CB!382.entry
見第2個參考解答
感謝指正, 已修正
如果照你的 RegExp 解法
用 C 的 scanf() 也可以解喔XD
張貼留言