You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C++中不使用正则表达式去除句子中的重复单词?

解决C++去除句子重复单词的问题

你的代码存在两个关键问题,导致最后一个单词重复输出:

  • 错误使用do-while循环:do-while会先执行循环体再判断流的状态,当流读完所有单词后,仍会进入循环体执行ss >> word,此时读取失败,但word可能保留上一次的内容,引发不必要的判断。
  • 错误使用while循环判断单词存在性:这里只需要一次判断(用if)即可,while循环属于冗余逻辑,虽然当前场景下不会直接引发重复,但不符合代码逻辑的合理性。

修改后的代码

#include <iostream>
#include <sstream>
#include <unordered_set>
#include <string>

using namespace std;

void removeDupWord(string str)
{
    istringstream ss(str);
    unordered_set<string> hsh;
    string word;

    // 改用while循环读取单词,仅当成功读取时进入循环体
    while (ss >> word) {
        // 用if判断单词是否未被访问过
        if (hsh.find(word) == hsh.end()) {
            cout << word << " ";
            hsh.insert(word);
        }
    }
    // 可选:添加换行,避免输出末尾的多余空格
    cout << endl;
}

// 测试示例
int main() {
    string input = "Welcome to to the world of of digital computers computers.";
    removeDupWord(input);
    return 0;
}

优化:避免末尾多余空格

如果希望输出结果末尾没有多余的空格,可以先将结果存储在字符串中再输出:

void removeDupWord(string str)
{
    istringstream ss(str);
    unordered_set<string> hsh;
    string word;
    string result;

    while (ss >> word) {
        if (hsh.find(word) == hsh.end()) {
            if (!result.empty()) {
                result += " ";
            }
            result += word;
            hsh.insert(word);
        }
    }
    cout << result << endl;
}

内容的提问来源于stack exchange,提问作者user15382501

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 22:40:25