Find substring range of NSString with unicode characters

放肆的年华 提交于 2019-12-24 12:45:36

问题


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?


回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/28622981/find-substring-range-of-nsstring-with-unicode-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!