I was getting the NSString from UIWebView which contain iPhone emoji and reversing text excluding emoji. I need to display reverse of NSString again in UIWebView but couldn’t get the reversed string with emoji. I am not identifying the emoji character in string. I have xcode 4.5 with iOS 6.0. here is my code:
- (NSString *) createReverseStringFromString:(NSString *)inputString {
if (inputString.length <= 0)
return inputString;
NSMutableString *mutableReverseString = [[NSMutableString alloc]
initWithCapacity:inputString.length];
Thfor (NSInteger i = inputString.length -1; i >= 0; i--) {
NSString *characterString = [inputString substringWithRange:NSMakeRange(i, 1)];
[mutableReverseString appendString:characterString];
NSLog(@"mutableReverseString..%@",mutableReverseString);
}
NSString *outputString = [mutableReverseString copy];
[mutableReverseString release];
return [outputString autorelease];
}
The problem is that many emoji characters are internally stored as a “surrogate pair” of two characters.
For example, “THUMBS UP SIGN” is Unicode point U+1F44D, but if you store it in an
NSStringand usesubstringWithRangeto get single characters, you will get two characters:which is the UTF-16 surrogate pair for U+1F44D.
Of course, if you reverse these two characters, the output is garbage.
The solution is to use
rangeOfComposedCharacterSequenceAtIndexto get sequences of characters which “belong together”:This function correctly reverses strings containing emoji characters.
(Note: I have omitted all
release,autoreleasecalls because I always compile with ARC. You have to add that again where appropriate.)