1

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.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
HurkNburkS
  • 5,492
  • 19
  • 100
  • 183

3 Answers3

12

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);
CodaFi
  • 43,043
  • 8
  • 107
  • 153
  • Either you meant `strcmp` or you forgot a parameter to `strncmp`. – rmaddy Feb 28 '13 at 21:26
  • Looks like `if (strcmp(myChar, str.UTF8String))` should be `if (strcmp(myChar, str.UTF8String) == 0)` if you want to check if strings are equal. http://www.cplusplus.com/reference/cstring/strcmp/ – Jaroslav Feb 18 '20 at 09:32
4

Better still:

 [str isEqualToString: @(myChar) ];

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

Mark Bernstein
  • 2,090
  • 18
  • 23
  • Actually, this is miles better than a cast. Only a subset of Core Foundation types can be safely cast back and forth to ObjC objects – CodaFi Feb 28 '13 at 22:43
  • CodaFi: since I suspected that the original poster came from a C/C++ background, I meant "no worse than a legitimate and safe cast", which is still deprecated but tolerated. (ObjC custom is far more tolerant of casting, because run-time support is better) – Mark Bernstein Mar 01 '13 at 01:24
0

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

Sebastian
  • 7,670
  • 5
  • 38
  • 50