简体   繁体   中英

Find substring range of NSString with unicode characters

If I have a string like this.

NSString *string = @"😀1😀3😀5😀7😀"

To get a substring like @"3😀5" you have to account for the fact the smiley face character take two bytes.

NSString *substring = [string substringWithRange:NSMakeRange(5, 4)];

Is there a way to get the same substring by using the actual character index so NSMakeRange(3, 3) in this case?

Make a swift extension of NSString and use new swift String struct. Has a beautifull String.Index that uses glyphs for counting characters and range selecting. Very usefull is cases like yours with emojis envolved

Thanks to @Joe's link I was able to create a solution that works.

This still seems like a lot of work for just trying to create a substring at unicode character ranges for an NSString. Please post if you have a simpler solution.

@implementation NSString (UTF)
- (NSString *)substringWithRangeOfComposedCharacterSequences:(NSRange)range
{
    NSUInteger codeUnit = 0;
    NSRange result;
    NSUInteger start = range.location;
    NSUInteger i = 0;
    while(i <= start)
    {
        result = [self rangeOfComposedCharacterSequenceAtIndex:codeUnit];
        codeUnit += result.length;
        i++;
    }

    NSRange substringRange;
    substringRange.location = result.location;
    NSUInteger end = range.location + range.length;
    while(i <= end)
    {
        result = [self rangeOfComposedCharacterSequenceAtIndex:codeUnit];
        codeUnit += result.length;
        i++;
    }   

    substringRange.length = result.location - substringRange.location;
    return [self substringWithRange:substringRange];
}
@end

Example:

NSString *string = @"😀1😀3😀5😀7😀";
NSString *result = [string substringWithRangeOfComposedCharacterSequences:NSMakeRange(3, 3)];   
NSLog(@"%@", result); // 3😀5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM