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

杀马特。学长 韩版系。学妹 提交于 2020-02-18 14:01:12

问题


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 character. Currently, I have a string that contains special characters such as std::string = "!@#$%^&". I then use the std::find_first_of () algorithm to check if any of the special characters are present in the string.

I was wondering how to do it based on whitelisting. I want to specify the lowercase/uppercase characters, numbers and an underscore in a string ( I don't want to list them. Is there any way I can specify the ascii range of some sort like [a-zA-Z0-9_]). How can I achieve this? Then I plan to use the std::find_first_not_of(). In this way I can mention what I actually want and check for the opposite.


回答1:


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



回答2:


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)



回答3:


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




回答4:


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.




回答5:


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




回答6:


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.




回答7:


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';
}



回答8:


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.



来源:https://stackoverflow.com/questions/6605282/how-can-i-check-if-a-string-has-special-characters-in-c-effectively

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!