How can I check if a string has special characters in C++ effectively?

前端 未结 9 850
情话喂你
情话喂你 2021-02-08 13:15

I am trying to find if there is better way to check if the string has special characters. In my case, anything other than alphanumeric and a \'_\' is considered a special charac

9条回答
  •  别跟我提以往
    2021-02-08 13:59

    Using

        s.erase(std::remove_if(s.begin(), s.end(), my_predicate), s.end());
    
        bool my_predicate(char c)
        {
         return !(isalpha(c) || c=='_');
        }
    

    will get you a clean string s.

    Erase will strip it off all the special characters and is highly customisable with the my_predicate function.

提交回复
热议问题