C++ 统计一行字符中的单词个数
C++ 统计一行字符中的单词个数
本文将介绍使用 C++ 代码统计一行字符中单词个数的方法。以空格为分隔符,将字符串中的单词分割开并进行统计。
代码示例:
#include <iostream>
#include <string>
#include <sstream>
int countWords(std::string input) {
std::stringstream ss(input);
std::string word;
int count = 0;
while (ss >> word) {
count++;
}
return count;
}
int main() {
std::string line;
std::cout << '请输入一行字符:';
getline(std::cin, line);
int wordCount = countWords(line);
std::cout << '单词个数为:' << wordCount << std::endl;
return 0;
}
代码解释:
countWords函数:- 该函数接收一个字符串作为输入,并返回该字符串中的单词个数。
- 使用
std::stringstream将输入字符串分割成多个单词,并使用一个计数器来统计单词个数。 ss >> word操作从字符串流ss中读取下一个单词到word变量中,直到读取到文件末尾。
main函数:- 从用户输入获取一行字符,存储在
line变量中。 - 调用
countWords函数统计line中的单词个数,并将结果存储在wordCount变量中。 - 将
wordCount的值输出到控制台。
- 从用户输入获取一行字符,存储在
运行结果:
例如,输入 “This is a test string.”,则输出结果为 “单词个数为:5”。
总结:
本代码使用 C++ 字符串流和计数器实现了一行字符中单词个数的统计功能。可以根据需要修改代码来处理其他分隔符或更复杂的情况。
原文地址: https://www.cveoy.top/t/topic/pgHZ 著作权归作者所有。请勿转载和采集!