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

前端 未结 9 846
情话喂你
情话喂你 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:55

    If you want this, but don't want to go the whole hog and use regexps, and given you're test is for ASCII chars - just create a function to generate the string for find_first_not_of...

    #include <iostream>
    #include <string>
    
    std::string expand(const char* p)
    {
        std::string result;
        while (*p)
            if (p[1] == '-' && p[2])
            {
                for (int c = p[0]; c <= p[2]; ++c)
                    result += (char)c;
                p += 3;
            }
            else
                result += *p++;
        return result;
    }
    
    int main()
    {
        std::cout << expand("A-Za-z0-9_") << '\n';
    }
    
    0 讨论(0)
  • 2021-02-08 13:57

    The first thing that you need to consider is "is this ASCII only"? If you answer is yes, I would encourage you to really consider whether or not you should allow ASCII only. I currently work for a company that is really having some headaches getting into foreign markets because we didn't think to support unicode from the get-go.

    That being said, ASCII makes it really easy to check for non alpha numerics. Take a look at the ascii chart.

    http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters

    • Iterate through each character
    • Check if the character is decimal value 48 - 57, 65 - 90, 97 - 122, or 95 (underscore)
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题