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

如何在C++中移除字符串中以指定字符开头的所有单词

C++移除指定字符开头单词的实现方案

你的思路是否正确?

你的思路方向没问题,但要留意几个容易踩坑的细节:

  • 如果目标单词是字符串的第一个词,得确保能正确识别并移除,不能漏处理
  • 如果目标单词在字符串末尾,后面没有空格,要处理到字符串结束,不能留尾巴
  • 移除单词后要避免出现连续空格,比如删除中间单词后,前后的空格要合并成一个

几种实用的C++实现方法

1. 字符串流拆分法(最省心)

用stringstream把原字符串拆成单个单词,逐个判断是否保留,最后拼接结果。这种写法清晰易懂,自动处理连续空格,几乎不会出错,适合大多数场景。

代码示例:

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

std::string removeWordsStartingWith(std::string input, char target) {
    std::istringstream iss(input);
    std::string word, result;
    while (iss >> word) {
        if (word.front() != target) {
            if (!result.empty()) result += " ";
            result += word;
        }
    }
    return result;
}

int main() {
    std::string str = "She made up her mind to meet up with him in the morning";
    std::cout << removeWordsStartingWith(str, 'm') << std::endl;
    // 输出:She up her to up with him in the
    return 0;
}

2. 原地修改字符串(内存高效)

如果要避免额外内存开销,直接在原字符串上操作,用双指针标记保留内容的位置,跳过要删除的单词。这种方法内存占用低,适合处理超大字符串。

代码示例:

#include <string>

std::string removeWordsStartingWith(std::string input, char target) {
    size_t writePos = 0;
    const size_t n = input.size();
    size_t i = 0;

    while (i < n) {
        // 保留开头的空格
        while (i < n && input[i] == ' ') {
            input[writePos++] = input[i++];
        }
        if (i >= n) break;

        // 遇到要删除的单词,跳过整个词
        if (input[i] == target) {
            while (i < n && input[i] != ' ') i++;
        } else {
            // 保留当前单词
            while (i < n && input[i] != ' ') {
                input[writePos++] = input[i++];
            }
        }
    }

    // 清理末尾多余的空格
    if (writePos > 0 && input[writePos - 1] == ' ') writePos--;
    input.resize(writePos);
    return input;
}

3. 正则表达式法(最简洁)

C++11及以上支持正则表达式,用regex_replace直接匹配并移除目标单词,不过要处理替换后产生的连续空格和首尾空格。这种写法最简洁,但性能略逊于前两种,适合快速实现小场景。

代码示例:

#include <string>
#include <regex>

std::string removeWordsStartingWith(std::string input, char target) {
    // 构建匹配规则:以target开头的单词
    std::regex wordReg("\\b" + std::string(1, target) + "\\w+\\b");
    std::string result = std::regex_replace(input, wordReg, "");
    
    // 合并连续空格
    result = std::regex_replace(result, std::regex("\\s+"), " ");
    // 去掉首尾空格
    if (!result.empty() && result.front() == ' ') result = result.substr(1);
    if (!result.empty() && result.back() == ' ') result = result.substr(0, result.size() - 1);
    return result;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 14:16:46