Search code examples
objective-cnsstringconst-char

Compare Objective-C const char with NSString


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.


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