3

I have a NSArray containing NSStrings with emoji codes in the following format:

0x1F463

How can I now convert them into a NSString with the correct format?

With this method I am able to generate an "Emoji"-NSString:

NSString *emoji = [NSString stringWithFormat:@"\U0001F463"];

But this is only possible with constant NSStrings. How can I convert the whole NSArray?

patrickS
  • 3,590
  • 4
  • 29
  • 40
  • `-stringWithFormat:` isn't *generating* anything - you're doing that yourself in the string constant you're feeding it. (Not to mention that you're abusing `-stringWithFormat:` anyway; you're not providing a formatting string to it.) What I don't understand is what's wrong with the strings in your array. Why don't they work as they are? – Extra Savoir-Faire Dec 22 '12 at 01:41
  • I have to convert the string "0x1F463" to "\U0001F463" to gent the unicode character which is an emoji. But I get the NSArray from an external plist – patrickS Dec 22 '12 at 01:47
  • So you're saying your array contains strings that *literally* contain "0x1F463", right? – Extra Savoir-Faire Dec 22 '12 at 01:48
  • possible duplicate of [iOS 5: How to convert an Emoji to a unicode character?](http://stackoverflow.com/questions/8635393/ios-5-how-to-convert-an-emoji-to-a-unicode-character) – durron597 Sep 04 '15 at 13:42

2 Answers2

4

Not my best work, but it appears to work:

for (NSString *string in array)
{
    @autoreleasepool {
        NSScanner *scanner = [NSScanner scannerWithString:string];
        unsigned int val = 0;
        (void) [scanner scanHexInt:&val];
        NSString *newString = [[NSString alloc] initWithBytes:&val length:sizeof(val) encoding:NSUTF32LittleEndianStringEncoding];
        NSLog(@"%@", newString);
        [newString release]; // don't use if you're using ARC
    }
}

Using an array of four of your sample value, I get four pairs of bare feet.

Extra Savoir-Faire
  • 6,026
  • 4
  • 29
  • 47
2

You can do it like this:

NSString *str = @"0001F463";
// Convert the string representation to an integer
NSScanner *hexScan = [NSScanner scannerWithString:str];
unsigned int hexNum;
[hexScan scanHexInt:&hexNum];
// Make a 32-bit character from the int
UTF32Char inputChar = hexNum;
// Make a string from the character
NSString *res = [[NSString alloc] initWithBytes:&inputChar length:4 encoding:NSUTF32LittleEndianStringEncoding];
// Print the result
NSLog(@"%@", res);
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523