Search code examples
iosstringspecial-charactersunichar

Detect underscore and caret characters in iOS/objective-C


I need to detect whether a unichar is equal to an underscore (_) or a caret (^). I'm currently doing it like this:

unichar ch;
NSString *chAsString = [NSString stringWithFormat:@"%C", ch];
if ([chAsString isEqualToString:@"_"])
    // ... do something ...
else if ([chAsString isEqualToString:@"^"])
    // ... do something else...

Question #1: Is this method safe, i.e., will I catch all possible encodings of these characters?

Question #2: Is this the cleanest way to do this? It seems awfully clunky. But I get the sense it is more reliable than if (ch == 0x5F), etc.


Solution

  • You don't have to compare string. You can compare each character. Try this:

    if (ch == '_')
        // ... do something ...
    else if (ch == '^')
        // ... do something else...
    

    Hope this helps.. :)