C++ 统计一行字符中单词个数的代码示例
C++ 统计一行字符中单词个数的代码示例
本文提供一个使用 C++ 语言编写的代码示例,该示例可以统计一行字符中的单词个数。代码利用 std::istringstream 类将输入字符串按空格分割为多个单词,并使用 std::vector 容器存储这些单词,最终返回单词数量。
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
int countWords(const std::string& line) {
std::vector<std::string> words;
std::istringstream iss(line);
std::string word;
while (iss >> word) {
words.push_back(word);
}
return words.size();
}
int main() {
std::string line;
std::cout << '请输入一行字符:';
std::getline(std::cin, line);
int wordCount = countWords(line);
std::cout << '单词个数:' << wordCount << std::endl;
return 0;
}
在上述代码中,使用了 std::istringstream 类来将输入的字符串按空格分割为多个单词,并将其存储在 std::vector 容器中。然后,通过返回 words.size() 来获取单词的个数。最后,在 main() 函数中,使用 std::getline() 函数获取输入的一行字符,并调用 countWords() 函数进行统计并输出结果。
原文地址: https://www.cveoy.top/t/topic/pgHV 著作权归作者所有。请勿转载和采集!