Would there be a better way to do this using alogrithm functions like std::find()?
std::string s = "012X012Y012";
//After erasing the numbers from beginning and end; the end result should be X012Y
size_t index = s.find_first_not_of("0123456789");
string::iterator iter_end = s.begin();
advance(iter_end, index);
s.erase(s.begin(), iter_end);
//Now std::string should be X012Y012
size_t index = s.find_last_not_of("0123456789")+1;
string::iterator iter_start = s.begin();
advance(iter_start, index);
s.erase(iter_start, s.end());
//Finally, std::string should be X012Y
Seems fine enough. I’d factor out your constant:
And re-use that.
erasedoes allow you to use indices instead of iterators, so you can trim all that iterator stuff from your code. You should also check the results of your search, otherwise you’ll do weird things to your string:Lastly, I think you should trim the right before the left. If you trim the left first, during
erasethe remainder of the string needs to be copied and moved down. By trimming the right first, you eliminate some things to copy. Nothing major, I suspect, but might as well.(This is true of most sequence containers: erasing from some point to the end simply means getting rid of objects, while erasing from the start to some point requires moving the remaining items into their new spot.)
Of course, you can generalize this and re-use it: