在C++中统计字符串中的单词数量,常用的方法包括使用std::stringstream自动分割和手动遍历字符判断边界,以下是具体实现和说明:
方法1:使用std::stringstream(推荐)std::stringstream会自动按空白字符(空格、制表符、换行符等)分割字符串,无需手动处理连续空白或边界情况,适合大多数场景。
- 核心逻辑:通过ss >> word逐个提取单词,每次成功提取时计数器count加1。
- 优点:代码简洁,自动跳过连续空白,结果准确。
- 示例代码:#include <iostream>#include <string>#include <sstream>using namespace std;int countWords(const string& str) { stringstream ss(str); string word; int count = 0; while (ss >> word) { // 自动跳过空白字符 ++count; } return count;}int main() { string text = " Hello world from C++ "; cout << "单词数量: " << countWords(text) << endl; // 输出:4 return 0;}
方法2:手动遍历字符判断边界通过逐个检查字符的状态变化(从非空白到空白或反之)判断单词边界,适用于需要自定义分隔规则(如排除标点符号)的场景。
方法3:使用STL算法(高级技巧)通过std::adjacent_find或迭代器扫描边界,但实现较复杂,通常用于学习STL用法,实际开发中不推荐。
- 核心逻辑:查找相邻字符是否满足分隔条件(如一个为非空白,下一个为空白)。
- 缺点:代码冗长,易出错,仅建议作为STL练习。
方法对比与选择建议- 常规需求:优先使用std::stringstream,代码简洁且不易出错。
- 自定义分隔规则:选择手动遍历,例如需排除标点符号时,可扩展条件判断:bool isDelimiter(char ch) { return ch == ' ' || ch == 't' || ch == 'n' || ch == ',' || ch == '.';}int countWordsCustom(const string& str) { bool inWord = false; int count = 0; for (char ch : str) { if (!isDelimiter(ch)) { if (!inWord) { inWord = true; ++count; } } else { inWord = false; } } return count;}
注意事项- 连续空白处理:std::stringstream和手动遍历均能正确处理连续空格、制表符或换行符。
- 边界情况:开头或结尾的空白字符不会影响计数结果。
- 性能:std::stringstream在大多数场景下性能足够,手动遍历在极端情况下可能更高效。
通过上述方法,可灵活应对不同场景下的单词统计需求。