溫馨提示×

c++怎么統計單詞個數

c++
小億
619
2023-11-21 03:54:00
欄目: 編程語言

在C++中,可以使用以下方法來統計單詞個數:

  1. 使用字符串流(stringstream)和循環來逐個讀取單詞并計數。
#include <iostream>
#include <sstream>

int countWords(const std::string& sentence) {
    std::stringstream ss(sentence);
    std::string word;
    int count = 0;

    while (ss >> word) {
        count++;
    }

    return count;
}

int main() {
    std::string sentence = "Hello world, this is a sentence.";
    int wordCount = countWords(sentence);
    std::cout << "Word count: " << wordCount << std::endl;

    return 0;
}
  1. 使用字符串的find_first_of函數和循環來逐個找到單詞并計數。
#include <iostream>
#include <string>

int countWords(const std::string& sentence) {
    int count = 0;
    size_t pos = sentence.find_first_of(" \t\n");

    while (pos != std::string::npos) {
        count++;
        pos = sentence.find_first_of(" \t\n", pos + 1);
    }

    return count + 1;
}

int main() {
    std::string sentence = "Hello world, this is a sentence.";
    int wordCount = countWords(sentence);
    std::cout << "Word count: " << wordCount << std::endl;

    return 0;
}

這些方法可以根據空格、制表符、換行符等作為單詞的分隔符進行統計。請根據實際需求選擇使用。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女