Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove all substrings from a string

How to remove all instances of the pattern from a string?

string str = "red tuna, blue tuna, black tuna, one tuna";
string pattern = "tuna";
like image 649
PrankCall Avatar asked Sep 07 '15 09:09

PrankCall


1 Answers

Removes all instances of the pattern from a 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;
}
like image 187
Deadlock Avatar answered Oct 14 '22 21:10

Deadlock