遍歷字串,維護布林狀態 in_word:
in_word = false。!in_word:單詞計數 +1,in_word = true。#include#include int count_words(const char *str) { int count = 0; bool in_word = false; while (*str) { if (isspace(*str)) { in_word = false; } else if (!in_word) { count++; in_word = true; } str++; } return count; } int main() { char line[1024]; fgets(line, sizeof(line), stdin); printf("單詞數: %d\n", count_words(line)); return 0; }
isspace() 判斷空白,涵蓋空格、\t、\n、\r 等。輸入: "Hello world this is C" 輸出: 單詞數: 5