在C++中,可以使用以下方法來統計單詞個數:
#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;
}
#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;
}
這些方法可以根據空格、制表符、換行符等作為單詞的分隔符進行統計。請根據實際需求選擇使用。