Determine if a string contains only alphanumeric c

2019-01-22 12:58发布

问题:

I am writing a function that determines whether a string contains only alphanumeric characters and spaces. I am effectively testing whether it matches the regular expression ^[[:alnum:] ]+$ but without using regular expressions. This is what I have so far:

#include <algorithm>

static inline bool is_not_alnum_space(char c)
{
    return !(isalpha(c) || isdigit(c) || (c == ' '));
}

bool string_is_valid(const std::string &str)
{
    return find_if(str.begin(), str.end(), is_not_alnum_space) == str.end();
}

Is there a better solution, or a “more C++” way to do this?

回答1:

Looks good to me, but you can use isalnum(c) instead of isalpha and isdigit.



回答2:

And looking forward to C++0x, you'll be able to use lambda functions (you can try this out with gcc 4.5 or VS2010):

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


回答3:

You can also do this with binders so you can drop the helper function. I'd recommend Boost Binders as they are much easier to use then the standard library binders:

bool string_is_valid(const std::string &str)
{
    return find_if(str.begin(), str.end(),
        !boost::bind(isalnum, _1) || boost::bind(std::not_equal_to<char>, _1, ' ')) == str.end();
}


回答4:

Minor points, but if you want is_not_alnum_space() to be a helper function that is only visible in that particular compilation unit, you should put it in an anonymous namespace instead of making it static:

namespace {
bool is_not_alnum_space(char c)
{
    return !(isalpha(c) || isdigit(c) || (c == ' '));
}
}
...etc