輸入一行字元,統計其中單詞個數。單詞之間由空白字元(空格、Tab、換行)分隔。進階需求:單詞以字母為主體,遇到非字母字元視為單詞結束,支援標點符號混雜的情況。
核心邏輯:維護一個 in_word 旗標,掃描字串時,若當前字元非空白且前一字元為空白(或開頭),則單詞計數 +1。
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char str[81];
int count = 0, in_word = 0;
char c;
gets(str); // 注意:gets 不安全,教學用
for (int i = 0; (c = str[i]) != '\0'; i++) {
if (c == ' ') in_word = 0;
else if (!in_word) { in_word = 1; count++; }
}
printf("There are %d words in the line.\n", count);
return 0;
}
規則:連續字母構成單詞,非字母字元(數字、標點、空白)作為分隔符。掃描時,若當前字元是字母且下一字元非字母(或結尾),計數 +1。
#include <stdio.h>
#include <stdbool.h>
bool is_letter(char c) {
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
}
int main(void) {
char str[100];
int count = 0;
fgets(str, sizeof(str), stdin); // 更安全
for (int i = 0; str[i]; i++) {
if (is_letter(str[i]) && !is_letter(str[i+1]))
count++;
}
printf("There are %d words in the line.\n", count);
return 0;
}
| 特性 | 基礎版 | 進階版 |
|---|---|---|
| 分隔符定義 | 僅空格 | 任意非字母字元 |
| "Hello,world!" | 1 個單詞 | 2 個單詞 |
| "C99 標準" | 2 個單詞 | 2 個單詞(C、標準) |
| 安全性 | 使用 gets | 使用 fgets |
fgets 或動態分配。isalpha 可能誤判,需配合 setlocale 或自定義 Unicode 判斷。單詞統計看似簡單,實則考驗對「單詞定義」的理解與邊界條件處理。基礎版適合教學入門,進階版更貼近真實文本處理場景。實際專案中建議使用成熟庫(如 strtok、正則表達式)或成熟的 NLP 分詞工具。