Search code examples
objective-ccharacter-encoding

How to extract the `€` character at NSString's given index without the character corruption?


Suppose I have a pool of characters which I can use to generate a random string:

NSString* chars = @"-/:;()$&@\".,?!'[]{}#%^*+=_\\|~<>€£¥•abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

and suppose I have generated this string:

randomString = @"%[NQ6KC9SL?g£M€J";

when I try to extract the Euro character with statement below (when i is 14):

NSString* character = [NSString stringWithFormat:@"%c", [text characterAtIndex:i]];

I get:

(lldb) po character
¬

¬ is not . I suspect it's an encoding problem, but how do I handle it properly?

£, for example, is not causing this kind of issues.

My eventual goal is to tap the character on the screen keyboard with:

self.app.keys[character] tap

Since the key has a label label: '€', and not ¬, it's breaking my code.

I have tried to substitute with \u20AC in the chars pool, but that hasn't fixed my issue.


Solution

  • You have the wrong formatting character in your stringWithFormat -

    • %c is an 8 bit usigned character
    • %C is a 16 bit UTF-16 code unit

    Refer to Format Specifiers

    Change the %c to %C and your code will work