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