How do I check a string for valid characters in standard C?

I want to check a string for characters using C characters. Is there standard functionality? As far as I can see, GNU Lib C regex lib is not available in VC ++. What do you suggest for such a simple task. I don't want to include the PCRE library dependency. I would prefer a simpler implementation.

+2


source to share


2 answers


You can check if a string contains any character from a given character set with strcspn .

Edit: as suggested by Inshalla and maykeye, strspn, wcsspn might be more appropriate for your task.



You would use like strspn

this:

#define LEGAL_CHARS "ABCDEFGHIJLKMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

if (strspn(str, LEGAL_CHARS) < strlen(str))
{
    /* String is not legal */

      

+4


source


The obvious answer is: 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;
}

      

0


source







All Articles