輸入字串,單詞以空格分隔,統計單詞個數。例:「how are you」→ 3。
#include <stdio.h>
#include <string.h>
#define SIZE 1024
int main() {
char str[SIZE] = {0};
int count = 0;
printf("輸入字串: ");
fgets(str, SIZE, stdin); // 安全替代 gets
str[strcspn(str, "\n")] = 0; // 移除換行
int len = strlen(str);
for (int i = 0; i < len; i++) {
if (str[i] != ' ') { // 進入單詞
count++;
while (i < len && str[i] != ' ') i++; // 跳過整個單詞
}
}
printf("單詞數: %d\n", count);
return 0;
}
邏輯: 遇到非空格 → 計數 +1 → 內層迴圈跳過連續非空格 → 外層迴圈繼續掃描。
int main() {
char str[SIZE] = {0};
int count = 0, in_word = 0;
fgets(str, SIZE, stdin);
str[strcspn(str, "\n")] = 0;
for (int i = 0; str[i]; i++) {
if (str[i] == ' ') {
in_word = 0; // 離開單詞
} else if (!in_word) { // 進入新單詞
count++; in_word = 1;
}
}
printf("單詞數: %d\n", count);
return 0;
}
邏輯: in_word 標記是否在單詞內。空格重置旗標,非空格且旗標為 0 時計數並置旗標。
| 場景 | 方法一 | 方法二 |
|---|---|---|
| 前導空格 | 正確 | 正確 |
| 尾隨空格 | 正確 | 正確 |
| 多重空格 | 正確 | 正確 |
| 空字串 | 0 | 0 |
| 單詞含製表符 | 視為分隔符 | 視為分隔符 |
#include <ctype.h> // 將 str[i] == ' ' 改為 isspace((unsigned char)str[i]) // 涵蓋空格、製表符、換行、垂直製表、換頁、回車