C++提取字符串中间单词代码异常:输出中间字符而非目标单词
问题分析与修复方案
我明白你的问题啦——你现在的代码把字符串的中间字符当成中间单词输出了,核心问题是你混淆了「单词数量」和「字符串长度」的逻辑,而且统计单词、定位中间单词的步骤全错了。咱们一步步来梳理和修复:
原代码的核心问题
- 错误地用字符串长度来计算中间位置,而我们需要的是单词的数量
- 循环内重复定义
count变量,且非空格时的count++会跳过大量字符,导致空格(单词分隔符)统计完全不准 - 计算中间单词的逻辑完全偏离目标,没有定位到单词的边界
- 最后的反转操作完全没必要,因为你根本没拿到完整的单词
修复后的代码
#include <iostream> #include <string> using namespace std; int main() { string sentence; cout << "Enter a sentence:" << endl; getline(cin, sentence); // 获取用户输入的完整句子 // 第一步:统计单词总数(处理首尾空格、连续空格的情况) int word_count = 0; bool in_word = false; for (char c : sentence) { if (c != ' ') { if (!in_word) { word_count++; in_word = true; } } else { in_word = false; } } if (word_count == 0) { cout << "No words entered!" << endl; return 0; } // 第二步:计算中间单词的索引(索引从0开始) int target_word_index; if (word_count % 2 == 1) { // 单词数为奇数,取正中间的单词 target_word_index = (word_count - 1) / 2; } else { // 单词数为偶数,取两个中间单词中的第一个 target_word_index = (word_count / 2) - 1; } // 第三步:遍历句子,找到目标单词的起始和结束位置 int current_word_index = 0; size_t start_pos = 0; bool found = false; for (size_t i = 0; i <= sentence.length(); i++) { // 遇到空格或字符串结尾,说明一个单词结束 if (i == sentence.length() || sentence[i] == ' ') { if (current_word_index == target_word_index) { // 提取从start_pos到当前位置的子串(排除空格) string middle_word = sentence.substr(start_pos, i - start_pos); cout << "Middle word is: " << middle_word << endl; found = true; break; } // 跳过后续的连续空格,定位下一个单词的起始位置 while (i < sentence.length() && sentence[i] == ' ') { i++; } start_pos = i; current_word_index++; } } if (!found) { cout << "Could not find the middle word!" << endl; } return 0; }
代码说明
- 单词统计:通过
in_word标记来处理连续空格和首尾空格,确保准确统计单词数量 - 目标索引计算:根据单词数的奇偶性,确定要提取的中间单词的索引(从0开始计数)
- 单词提取:遍历句子,定位每个单词的起始和结束位置,找到目标索引对应的单词后提取输出
测试一下输入hello there friend(3个单词,奇数),会输出there;输入one two three four(4个单词,偶数),会输出two,完全符合你的需求。
内容的提问来源于stack exchange,提问作者namikaze123
相关产品推荐
相关产品推荐

