Reputation: 14553
I'm wondering, is there a way to detect a character that takes up more than 1 index spot in an NSString? (like an emoji). I'm trying to implement a custom text view and when the user pushes delete, I need to know if I should delete only the previous one index spot or more.
Upvotes: 1
Views: 94
Reputation: 37189
Actually NSString
use UTF-16
.So it is quite difficult to work with characters which takes two UTF-16 charater(unichar) or more
.But you can do with rangeOfComposedCharacterSequenceAtIndex
to get range and than delete.
First find the last character index from string
NSUInteger lastCharIndex = [str length] - 1;
Than get the range of last character
NSRange lastCharRange = [str rangeOfComposedCharacterSequenceAtIndex: lastCharIndex];
Than delete with range from character (If it is of two UTF-16 than it deletes UTF-16)
deletedLastCharString = [str substringToIndex: lastCharRange.location];
You can use this method with any type of characters
which takes any number of unichar
Upvotes: 3
Reputation: 3701
For one you could transform the string to a sequence of characters using [myString UTF8String]
and you can then check if the character has its first bit set to one or zero. If its one then this is a UTF8 character and you can then check how many bytes are there to this character. Details about UTF8 can be found on Wikipedia - UTF8. Here is a simple example:
NSString *string = @"ČTest";
const char *str = [string UTF8String];
NSMutableString *ASCIIStr = [NSMutableString string];
for (int i = 0; i < strlen(str); ++i)
if (!(str[i] & 128))
[ASCIIStr appendFormat:@"%c", str[i]];
NSLog(@"%@", ASCIIStr); //Should contain only ASCII characters
Upvotes: 1