C++实现段落按句号分割句子的最大单词数统计问题求解
问题修复方案
问题根源
- 按句号分割后,除首个句子外其余句子开头自带前导空格,原有直接统计空格数的逻辑会把前导空格算成单词间隔,导致计数偏大
- 未过滤分割生成的空字符串,遍历固定8次时空字符串会被错误统计为1个单词
- 未存储每个句子对应的单词数,无法直接完成排序/取最大值的需求
最易理解的修复思路
- 改写
countWords函数,使用stringstream自动过滤空格统计单词,彻底避免前导空格、连续空格、空字符串的统计错误 - 改造
split函数返回实际分割得到的有效句子数量,避免遍历无效空元素 - 存储每个句子的单词数后,使用
std::sort配合lambda完成降序排序,取第一个元素即为最大单词数
修复后完整代码
#include <iostream> #include <string> #include <sstream> #include <algorithm> #define max 8 // 定义最大字符串数量 using namespace std; string strings[max]; // 自定义分割函数,返回实际分割得到的句子数量 int split (string str, char seperator) { int currIndex = 0, i = 0; int startIndex = 0, endIndex = 0; int validCount = 0; while (i <= str.size()) { if (str[i] == seperator || i == str.size()) { endIndex = i; string subStr = ""; subStr.append(str, startIndex, endIndex - startIndex); // 仅存储非空句子 if (subStr.size() > 0 && subStr != " ") { strings[currIndex] = subStr; currIndex += 1; validCount++; } startIndex = endIndex + 1; } i++; } return validCount; } // 改写后的单词统计函数,使用stringstream自动处理空格问题 int countWords(string str) { int count = 0; string word; stringstream ss(str); // 每次提取一个单词,自动跳过所有空格、换行、制表符等空白字符 while (ss >> word) { count++; } return count; } int main() { string str = "Program to split strings. By using custom split function. In C++"; char seperator = '.'; int validSentenceCount = split(str, seperator); int wordCounts[validSentenceCount]; // 存储每个句子的单词数 cout << "分割后的句子及对应单词数:" << endl; for (int i = 0; i < validSentenceCount; i++) { wordCounts[i] = countWords(strings[i]); cout << "句子" << i+1 << ":" << strings[i] << ",单词数:" << wordCounts[i] << endl; } // 用std::sort+lambda实现降序排序 sort(wordCounts, wordCounts + validSentenceCount, [](int a, int b) { return a > b; }); cout << endl << "按句号分割的句子最大单词数为:" << wordCounts[0] << endl; return 0; }
运行结果
分割后的句子及对应单词数: 句子1:Program to split strings,单词数:4 句子2: By using custom split function,单词数:5 句子3: In C++,单词数:2 按句号分割的句子最大单词数为:5
内容的提问来源于stack exchange,提问作者MpcHAG
相关产品推荐
相关产品推荐

