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

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);   

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)

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(),
        [](unsigned 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.


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).