tags:

views:

116

answers:

2

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
That would be for checking against illegal characters.
anon
You want strspn for the other thing :-)
Inshallah
strspn then. Or wcsspn for more unicode-friendly application.Or std::string::find_first_not_of.
maykeye
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