Remove characters from std::string from "(" to ")" with erase ?

JAN picture JAN · Dec 14, 2012 · Viewed 8.8k times · Source

I want to remove the substring of my string , it looks something like this :

At(Robot,Room3)

or

SwitchOn(Room2)

or

SwitchOff(Room1)

How can I remove all the characters from the left bracket ( to the right bracket ) , when I don't know their indexes ?

Answer

bames53 picture bames53 · Dec 14, 2012

If you know the string matches the pattern then you can do:

std::string str = "At(Robot,Room3)";
str.erase( str.begin() + str.find_first_of("("),
           str.begin() + str.find_last_of(")"));

or if you want to be safer

auto begin = str.find_first_of("(");
auto end = str.find_last_of(")");
if (std::string::npos!=begin && std::string::npos!=end && begin <= end)
    str.erase(begin, end-begin);
else
    report error...

You can also use the standard library <regex>.

std::string str = "At(Robot,Room3)";
str = std::regex_replace(str, std::regex("([^(]*)\\([^)]*\\)(.*)"), "$1$2");