Question

I was wondering if there is a simple way to compare a const char with an NSString, or do I have to convert the const char to an NSString before doing do?

I have been looking through Apple docs but struggling to find an answer to my question.

Était-ce utile?

La solution

Either

NSString *str = @"string";
const char *myChar = "some string";
if (strcmp(myChar,  str.UTF8String))

or

[str isEqualToString:[NSString stringWithUTF8String:myChar]];

The core foundation route is also an option:

CFStringRef myStr = CFSTR("some chars");

bool result = CFStringCompareWithOptions(myStr, ((__bridge CFStringRef)str),CFRangeMake(0,CFStringGetLength(myStr)), kCFCompareCaseInsensitive);

Autres conseils

Better still:

 [str isEqualToString: @(myChar) ];

This is no worse than a cast, which you're bound to need since the types are incommensurable.

You are comparing two different things, so you have to convert one to the other. Which way you convert is up to you.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top