首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在c++中删除子字符串形式的字符串

如何在c++中删除子字符串形式的字符串
EN

Stack Overflow用户
提问于 2014-09-24 14:37:58
回答 2查看 4.9K关注 0票数 1

这里有一个类似于这个WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB的字符串,我想删除所有的wub单词,然后得到这个结果WE ARE THE CHAMPIONS MY FRIEND

c++中有什么特殊的功能可以做吗?我找到了string::erase,但是那个继电器帮不了我!!

我可以用for循环来完成这个操作,找到这个单词表单字符串,然后删除它,但是我正在寻找更好的方法。有什么功能可以做吗??

EN

回答 2

Stack Overflow用户

发布于 2014-09-24 14:43:19

使用boost::algorithm::replace_all

代码语言:javascript
复制
#include <iostream>
#include <string>
#include <boost/algorithm/string/replace.hpp>

int main()
{
    std::string input="WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB";
    boost::algorithm::replace_all(input, "WUB", " ");
    std::cout << input << std::endl;
    return 0;
}
票数 2
EN

Stack Overflow用户

发布于 2014-09-24 14:55:40

删除所有发生的事情:

代码语言:javascript
复制
#include <iostream>

std::string removeAll( std::string str, const std::string& from) {
    size_t start_pos = 0;
    while( ( start_pos = str.find( from)) != std::string::npos) {
        str.erase( start_pos, from.length());
    }
    return str;
}

int main() {

    std::string s = "WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB";
    s = removeAll( s, "WUB");

    return 0;
}

http://ideone.com/Hg7Kwa

替换所有发生的情况:

代码语言:javascript
复制
std::string replaceAll(std::string str, const std::string& from, const std::string& to) {
    size_t start_pos = 0;
    while((start_pos = str.find(from, start_pos)) != std::string::npos) {
        str.replace(start_pos, from.length(), to);
        start_pos += to.length();
    }
    return str;
}

int main() {
    std::string s = "WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB";
    s = replaceAll( s, "WUB", " ");
    /* replace spaces */
    s = replaceAll( s, "  ", " ");

    return 0;
}

http://ideone.com/Yc8rGv

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26019701

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档