C++如何统计含不规则空格的字符串的单词数?代码输出异常如何解决?
问题分析与修复方案
现有代码的核心问题
- 语法错误:
else if((s[i] == ' ')分支存在两处问题,一是单引号只能包裹单个字符,多空格放在单引号里属于语法错误,二是该分支缺少右括号,代码无法正常编译。 - 单词计数逻辑错误:当前每遇到一个空格就给单词数+1,连续多个空格会被重复计数,自然不符合统计需求。
- 边界场景兼容差:初始化单词数为1,无法兼容空字符串、字符串首尾带空格的场景,会出现统计错误。
- 辅音统计错误:当前所有非元音、非空格的字符都会被统计为辅音,标点、数字、特殊符号都会被错误计入。
修正后代码
#include <iostream> #include <string> #include <cctype> using namespace std; int main() { string s = "how are you?"; int vowels = 0; int consonants = 0; int words = 0; bool in_word = false; // 标记当前是否处在单词内部 for(int i = 0; i < s.length(); i++) { char c = s[i]; if(isspace(c)) { in_word = false; } else { // 第一次进入单词范围,单词数+1 if(!in_word) { words++; in_word = true; } // 统计元音辅音 if(isalpha(c)) { if(c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U' || c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') { vowels++; } else { consonants++; } } } } cout << "number of vowels "<< vowels<< endl; cout << "number of words "<< words << endl; cout << "number of consonants "<< consonants << endl; return 0; }
修正说明
- 新增
in_word标记位,只有从空格切换到非空格字符时才统计为一个新单词,彻底解决连续空格重复计数的问题 - 引入
<cctype>库的isspace、isalpha工具函数,简化空格、字母判断逻辑,同时自动兼容全角空格以外的各类空白字符 - 调整辅音统计规则,只有英文字母才会参与元音、辅音统计,标点等特殊字符不会被错误计入辅音
- 单词数初始化为0,兼容空字符串、首尾带空格的各类边界场景
针对示例输入"how are you?",修正后代码的运行结果为:
number of vowels 5 number of words 3 number of consonants 4
内容的提问来源于stack exchange,提问作者PatrickLao
相关产品推荐
相关产品推荐

