Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 220
dreamlax Avatar asked May 28 '10 05:05

dreamlax


People also ask

How do I check if a string contains alphanumeric characters?

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.

How do you know if a string is only letters and spaces?

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.

How do you check if a string contains only alphabets and spaces in Python?

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 .


2 Answers

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

like image 179
jopa Avatar answered Oct 03 '22 08:10

jopa


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(); } 
like image 24
R Samuel Klatchko Avatar answered Oct 03 '22 08:10

R Samuel Klatchko