Search code examples
c++punctuationremove-if

C++ removing certain symbol/punctuation


token.erase(std::remove_if(token.begin(), token.end(), ispunct), token.end()); It seems that using ispunct will remove all punctuation. Is it possible to only remove certain types? For example if I want to remove all punctuation except, for example colon? Or do you have to write your own condition in that case?


Solution

  • Use a lambda (or a callable object) as the predicate of your token.erase(...) call:

    token.erase(
        std::remove_if(
            token.begin(), 
            token.end(), 
            [](char x){ return ispunct(x) && x != ':'; }), 
        token.end());