Reputation:
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.
Upvotes: 2
Views: 581
Reputation: 43130
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 */
Upvotes: 4
Reputation:
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;
}
Upvotes: 0