这里有一个类似于这个WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB的字符串,我想删除所有的wub单词,然后得到这个结果WE ARE THE CHAMPIONS MY FRIEND。
c++中有什么特殊的功能可以做吗?我找到了string::erase,但是那个继电器帮不了我!!
我可以用for循环来完成这个操作,找到这个单词表单字符串,然后删除它,但是我正在寻找更好的方法。有什么功能可以做吗??
发布于 2014-09-24 14:43:19
使用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;
}发布于 2014-09-24 14:55:40
删除所有发生的事情:
#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
https://stackoverflow.com/questions/26019701
复制相似问题