I want to validate a string against legal characters using standard C. Is there a standard functionality? As far as I can see, GNU Lib C's regex lib is not available in VC++. What do you suggest for implementing such a simple task. I don't want to include PCRE library dependency. I'd prefer a simpler implementation.
+4
A:
You can check if a string contains any character from a given set of characters with strcspn.
Edit: as suggested by Inshalla and maykeye, strspn, wcsspn might be more appropriate for your task.
You would use strspn
like so:
#define LEGAL_CHARS "ABCDEFGHIJLKMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
if (strspn(str, LEGAL_CHARS) < strlen(str))
{
/* String is not legal */
Nick D
2009-08-21 07:43:52
That would be for checking against illegal characters.
anon
2009-08-21 08:08:47
You want strspn for the other thing :-)
Inshallah
2009-08-21 08:10:54
strspn then. Or wcsspn for more unicode-friendly application.Or std::string::find_first_not_of.
maykeye
2009-08-21 08:14:25
A:
The obvious answer: write a function. Or in this case two functions:
int IsLegal( char c ) {
// test c somehow and return true if legal
}
int LegalString( const char * s ) {
while( * s ) {
if ( ! IsLegal( * s ) ) {
return 0;
}
s++;
}
return 1;
}
anon
2009-08-21 08:11:27