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?
Using Regular Expression The idea is to use the regular expression ^[a-zA-Z0-9]*$ , which checks the string for alphanumeric characters. This can be done using the matches() method of the String class, which tells whether this string matches the given regular expression.
To check if a string contains only letters and spaces, call the test() method on a regular expression that matches only letters and spaces. The test method will return true if the regular expression is matched in the string and false otherwise.
The Python isalpha() method returns the Boolean value True if every character in a string is a letter; otherwise, it returns the Boolean value False . In Python, a space is not an alphabetical character, so if a string contains a space, the method will return False .
Looks good to me, but you can use isalnum(c)
instead of isalpha
and isdigit
.
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With