简体   繁体   中英

How to validate a string against legal characters in standard C?

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.

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 */

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM