如何从c ++中的字符串中删除子字符串

时间:2014-09-24 14:37:58

标签: c++ string

此处我有一个类似WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB的字符串我要删除所有wub字词,并获得此结果WE ARE THE CHAMPIONS MY FRIEND
在c ++中是否有任何特定的功能,我发现string::erase但是那个继电器对我没有帮助!!
我可以使用for循环执行此操作并找到此单词形式字符串然后删除它,但我正在寻找更好的方法。 有什么功能可以做到吗???

3 个答案:

答案 0 :(得分:4)

您可以使用std::regex_replace

std::string s1 = "WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB";
std::regex target("(WUB)+");
std::string replacement = " ";
std::string s2 = std::regex_replace(s1, target, replacement);

LIVE DEMO

答案 1 :(得分:1)

使用boost :: algorithm :: replace_all

#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 :(得分:1)

删除所有出现次数:

#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


替换所有出现次数:

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