Here I have a string like this WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB I want to delete all wub word form this and get this result WE ARE THE CHAMPIONS MY FRIEND.
Is there any particular function in c++ to do that I found string::erase but that relay doesn't help me!!
I can do that with for loop and find this word form string then delete it but I'm looking for better way.
Is there any function to do this???
3 Answers
You could use std::regex_replace:
std::string s1 = "WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB";
std::regex target("(WUB)+");
std::string replacement = " ";
std::string s2 = std::regex_replace(s1, target, replacement);
4 Comments
Fred Larson
Given the OP's desired output, I think the replacement string should contain a space.
Fred Larson
Ah, and the updated regex replaces consecutive matches with a single space. Good work.
Daniel.V
@Paul R Thanks for your answer it worked prefectly but there should be space between each word in output
Paul R
@Daniel.V: I've updated the answer in the last minute or so to fix this - you might need to refresh the page in your browser?
Use 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;
}
5 Comments
Paul R
Could you expand your answer to give an example of how this would be applied ?
Paul R
Thanks - that's helpful. I guess this wouldn't cope with the OP's example exactly though, i.e.
WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB -> WE ARE THE CHAMPIONS MY FRIEND ?Nipun Talukdar
@PaulR we have to initialize input with "WUBWEWUBAREWUBWUBTHEWUBCHAMPIONSWUBMYWUBFRIENDWUB" and replacement with "WUB" in place of CD.
Paul R
Sure, but the "WUBWUB" between "ARE" and "THE" will give two spaces, not one ?
Nipun Talukdar
@PaulR Yes. I got the point now. regex_replace is the better option.
Erase all occurences:
#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;
}
Replace all occurences:
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;
}
std::regex_replace?boost::algorithm::replace_all