c++编写一个函数,接受一个字符串,计算并返回其中包含的单词个数。
作者:野牛程序员:2023-08-11 20:29:51 C++阅读 2634
c++编写一个函数,接受一个字符串,计算并返回其中包含的单词个数。
#include <iostream>
#include <string>
#include <sstream>
int countWords(const std::string& str) {
std::istringstream iss(str);
int count = 0;
std::string word;
while (iss >> word) {
count++;
}
return count;
}
int main() {
std::string text = "This is a test sentence.";
int wordCount = countWords(text);
std::cout << "Number of words: " << wordCount << std::endl;
return 0;
}野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

