c++

c++怎么统计单词个数

小亿
512
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
看了该问题的人还看了