-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.

2
  • 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. Commented Nov 2, 2015 at 15:00
  • @oo_miguel He could just replace AAA with an empty string. Therefore I'd say it is a duplicate. Commented Nov 2, 2015 at 15:06

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I had heard of replace but wanted to know if there was specificly used for removal. That will do it though.
@Q3SanD yeah right, in your case string::erase is even better. just adapted the answer
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.