Determine if a string contains only alphanumeric characters (or a space)

后端 未结 4 866
遇见更好的自我
遇见更好的自我 2020-12-14 00:49

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

相关标签:
4条回答
  • 2020-12-14 01:25

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

    0 讨论(0)
  • 2020-12-14 01:32

    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();
    }
    
    0 讨论(0)
  • 2020-12-14 01:36

    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();
    }
    
    0 讨论(0)
  • 2020-12-14 01:41

    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
    
    0 讨论(0)
提交回复
热议问题