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

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

    Try:

    std::string  x(/*Load*/);
    if (x.find_first_not_of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890_") != std::string::npos)
    {
        std::cerr << "Error\n";
    }
    

    Or try boost regular expressions:

    // Note: \w matches any word character `alphanumeric plus "_"`
    boost::regex test("\w+", re,boost::regex::perl);
    if (!boost::regex_match(x.begin(), x.end(), test)
    {
        std::cerr << "Error\n";
    }
    
    // The equivalent to \w should be:
    boost::regex test("[A-Za-z0-9_]+", re,boost::regex::perl);   
    
    0 讨论(0)
  • 2021-02-08 13:40

    There's no way using standard C or C++ to do that using character ranges, you have to list out all of the characters. For C strings, you can use strspn(3) and strcspn(3) to find the first character in a string that is a member of or is not a member of a given character set. For example:

    // Test if the given string has anything not in A-Za-z0-9_
    bool HasSpecialCharacters(const char *str)
    {
        return str[strspn(str, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_")] != 0;
    }
    

    For C++ strings, you can equivalently use the find_first_of and find_first_not_of member functions.

    Another option is to use the isalnum(3) and related functions from the <ctype.h> to test if a given character is alphanumeric or not; note that these functions are locale-dependent, so their behavior can (and does) change in other locales. If you do not want that behavior, then don't use them. If you do choose to use them, you'll have to also test for underscores separately, since there's no function that tests "alphabetic, numeric, or underscore", and you'll also have to code your own loop to search the string (or use std::find with an appropriate function object).

    0 讨论(0)
  • 2021-02-08 13:42

    I would just use the built-in C facility here. Iterate over each character in the string and check if it's _ or if isalpha(ch) is true. If so then it's valid, otherwise it's a special character.

    0 讨论(0)
  • 2021-02-08 13:43

    The functions (macros) are subject to locale settings, but you should investigate isalnum() and relatives from <ctype.h> or <cctype>.

    0 讨论(0)
  • 2021-02-08 13:44

    I think I'd do the job just a bit differently, treating the std::string as a collection, and using an algorithm. Using a C++0x lambda, it would look something like this:

    bool has_special_char(std::string const &str) {
        return std::find_if(str.begin(), str.end(),
            [](char ch) { return !(isalnum(ch) || ch == '_'); }) != str.end();
    }
    

    At least when you're dealing with char (not wchar_t), isalnum will typically use a table look up, so it'll usually be (quite a bit) faster than anything based on find_first_of (which will normally use a linear search instead). IOW, this is O(N) (N=str.size()), where something based on find_first_of will be O(N*M), (N=str.size(), M=pattern.size()).

    If you want to do the job with pure C, you can use scanf with a scanset conversion that's theoretically non-portable, but supported by essentially all recent/popular compilers:

    char junk;
    if (sscanf(str, "%*[A-Za-z0-9_]%c", &junk))
        /* it has at least one "special" character
    else
        /* no special characters */
    

    The basic idea here is pretty simple: the scanset skips across all consecutive non-special characters (but doesn't assign the result to anything, because of the *), then we try to read one more character. If that succeeds, it means there was at least one character that was not skipped, so we must have at least one special character. If it fails, it means the scanset conversion matched the whole string, so all the characters were "non-special".

    Officially, the C standard says that trying to put a range in a scanset conversion like this isn't portable (a '-' anywhere but the beginning or end of the scanset gives implementation defined behavior). There have even been a few compilers (from Borland) that would fail for this -- they would treat A-Z as matching exactly three possible characters, 'A', '-' and 'Z'. Most current compilers (or, more accurately, standard library implementations) take the approach this assumes: "A-Z" matches any upper-case character.

    0 讨论(0)
  • 2021-02-08 13:44

    You can use something like this:

    #include <ctype>
    
    for(int i=0;i<s.length();i++){
        if( !std::isalpha(s[i]) && !std::isdigit(s[i]) && s[i]!='_')
              return false
    }
    

    The isalpha() function checks whether it is alphanumeric or not and isdigit() checks whether it is digit.

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