Determine if a string contains only alphanumeric characters (or a space)
Posted
by dreamlax
on Stack Overflow
See other posts from Stack Overflow
or by dreamlax
Published on 2010-05-28T05:47:27Z
Indexed on
2010/05/28
5:51 UTC
Read the original article
Hit count: 263
I'm learning C++ and I am writing a function that determines whether a string contains only alphanumeric characters and spaces. I suppose I am effectively testing whether it matches the regular expression ^[[:alnum:] ]+$
but without using regular expressions. I have seen a lot of algorithms revolve around iterators, so I tried to find a solution that made use of iterators, and this is what I have:
#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?
© Stack Overflow or respective owner