Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

enum string comparison

Tags:

c

objective-c

I need to compare an enum as a whole to one string, so the whole contents of the enum is checked.

Wanted something like:

NSString *colString = [[NSString aloc] initWithString:@"threeSilver"];


typedef enum {
oneGreen,
twoBlue, 
threeSilver
}numbersAndColours;

if (colString == numbersAndColours) {
//Do cool stuff
}

But obviously I can't do that, maybe a struct... sorry, I'm new to C please help?

BTW: I know NSString isn't C, but figured this question was more C, than Obj-C.

Thanks

like image 382
Niceguy Avatar asked Jan 17 '10 22:01

Niceguy


1 Answers

In C you'd have to write a function for that. It would essentially be a switch statement.

char* colour_of(enum numbersAndColours c)
{
    switch( c ) {
    case oneGreen:
        return "oneGreen";
        break;
    case twoBlue:
        return "twoBlue";
        break;
    /* ... */
    default:
        return "donno";
    }
}

You can use the function then like so:

{
    char* nac;
    nac = colour_of(numbersAndColours);
    if( strncmp(colString, nac, colStringLen) == 0 )
        /* ... */
}

If colString doesn't match any of the enum elements it won't match numbersAndColours. There is no need to compare it against all of the elements.

like image 50
wilhelmtell Avatar answered Oct 19 '22 22:10

wilhelmtell