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

How to delete a substring form a string in c++

本文关键字:字符串 删除 c++      更新时间:2023-10-16

这里有一个类似于WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB的字符串,我想从中删除所有wub单词,并得到这个结果WE ARE THE CHAMPIONS MY FRIEND
c++中有什么特殊的函数可以做到这一点吗?我找到了string::erase,但那个继电器对我没有帮助
我可以用for循环找到这个单词形式的字符串,然后删除它,但我正在寻找更好的方法。有什么功能可以做到这一点吗???

您可以使用std::regex_replace:

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

现场演示

使用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;
}

清除所有发生:

#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