How to remove all substrings from a string

How to remove all instances of a template from a string?

string str = "red tuna, blue tuna, black tuna, one tuna"; string pattern = "tuna"; 
+6
source share
3 answers

Removes all instances of the template from the string,

 #include <string> #include <iostream> using namespace std; void removeSubstrs(string& s, string& p) { string::size_type n = p.length(); for (string::size_type i = s.find(p); i != string::npos; i = s.find(p)) s.erase(i, n); } int main() { string str = "red tuna, blue tuna, black tuna, one tuna"; string pattern = "tuna"; removeSubstrs(str, pattern); cout << str << endl; } 
+11
source

This is the main question, and you better take a look at the string capabilities in the standard library.

Classic solution

 #include <iostream> #include <string> int main() { std::string str = "red tuna, blue tuna, black tuna, one tuna"; std::string pattern = "tuna"; std::string::size_type i = str.find(pattern); while (i != std::string::npos) { str.erase(i, pattern.length()); i = str.find(pattern, i); } std::cout << str; } 

Example

RegEx Solution

With C ++ 11, you have another solution (thanks Joachim for reminding me of this) based on regular expressions

 #include <iostream> #include <string> #include <regex> int main() { std::string str = "red tuna, blue tuna, black tuna, one tuna"; std::regex pattern("tuna"); std::cout << std::regex_replace(str, pattern, ""); } 

Example

+7
source

Try something like:

 void replaceAll(std::string& str, const std::string& from, const std::string& to) { if(from.empty()) return; 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(); // In case 'to' contains 'from', like replacing 'x' with 'yx' } } 

From Replace part of a string with another string

+2
source

All Articles