-5

I have a string such as:

AAAbbbbbAAA

I'd like to remove all the occurances of a pattern AAA to get:

bbbbb

The pattern can occur anywhere in the string.

oo_miguel
  • 2,374
  • 18
  • 30
Grégoire Borel
  • 1,880
  • 3
  • 33
  • 55
  • 1
    @Linus this is not really a duplicate since he wants to remove the substring and not replace it. so string::erase is here even more adequate. – oo_miguel Nov 02 '15 at 15:00
  • @oo_miguel He could just replace `AAA` with an empty string. Therefore I'd say it is a duplicate. – Linus Nov 02 '15 at 15:06

2 Answers2

2

Given:

string yourstring("AAAbbbAAA");
string removestring("AAA");

You could simply run something like this multiple times on your string:

yourstring.erase(yourstring.find(removestring), removestring.length());

Of course you will have to check that string::find actually finds an occurence before using string::erase.

oo_miguel
  • 2,374
  • 18
  • 30
0

Here is the code. It's not very much efficient, but works well, and is a tiny code.

string h = "AAAbbbAAAB";

int pos = h.find("AAA");
while(pos!=-1)
{
    h.replace(pos, 3, "");
    pos = h.find("AAA");
}

cout << h << endl;

It only works if you know the pattern. If it doesn't what you want, maybe you're looking for a pattern matching algorithm, like KMP.