首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

統計一行字符中的單詞數 C 語言實現

     編輯:關於C++

問題

輸入一行字符串,統計單詞個數。單詞由字母數字組成,以空格分隔(連續空格視為一個分隔符,行首空格不計)。

狀態機思路

  • 狀態 in_word:當前是否在單詞內
  • 掃描每字符:
    • 若為空格:in_word = false
    • 若非空格且 !in_word:新單詞開始,count++,in_word = true

代碼實現

#include <cstdio>
#include <cstring>

int main() {
    char line[1000];
    fgets(line, sizeof(line), stdin);
    // 移除可能的換行符
    line[strcspn(line, "\n")] = '\0';

    int count = 0;
    bool in_word = false;
    for (char *p = line; *p; ++p) {
        if (*p == ' ') {
            in_word = false;
        } else if (!in_word) {
            in_word = true;
            ++count;
        }
    }
    printf("There are %d words in this line.\n", count);
    return 0;
}

關鍵點

  • fgets 讀整行含空格
  • 狀態機正確處理連續空格、行首空格
  • 時間 O(N),空間 O(1)

擴展:C++ string 版本

#include <iostream>
#include <string>
using namespace std;
int main() {
    string s; getline(cin, s);
    int cnt = 0; bool in = false;
    for (char c : s) {
        if (c == ' ') in = false;
        else if (!in) { in = true; ++cnt; }
    }
    cout << "There are " << cnt << " words in this line." << endl;
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved