Truncate string containing emoji or unicode characters at word or character boundaries

↘锁芯ラ 提交于 2019-11-29 03:57:05

NSString has a method rangeOfComposedCharacterSequencesForRange that you can use to find the enclosing range in the string that contains only complete composed characters. For example

NSString *s =  @"😄";
NSRange r = [s rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, 1)];

gives the range { 0, 2 } because the Emoji character is stored as two UTF-16 characters (surrogate pair) in the string.

Remark: You could also check if you can simplify your first loop by using

enumerateSubstringsInRange:options:usingBlock

with the NSStringEnumerationByWords option.

"truncate a string at a given length" <-- Do you mean length as in byte length or length as in number of characters? If the latter, then a simple substringToIndex: will suffice (check the bounds first though). If the former, then I'm afraid you'll have to do something like:

NSString *TruncateString(NSString *original, NSUInteger maxBytesToRead, NSStringEncoding targetEncoding) {
    NSMutableString *truncatedString = [NSMutableString string];

    NSUInteger bytesRead = 0;
    NSUInteger charIdx = 0;

    while (bytesRead < maxBytesToRead && charIdx < [original length]) {
        NSString *character = [original substringWithRange:NSMakeRange(charIdx++, 1)];

        bytesRead += [character lengthOfBytesUsingEncoding:targetEncoding];

        if (bytesRead <= maxBytesToRead)
            [truncatedString appendString:character];
    }

    return truncatedString;
}

EDIT: Your code can be rewritten as follows:

NSString *original = [_postDictionay objectForKey:@"message"];

NSArray *characters = [[original componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF != ''"]];

NSArray *truncatedCharacters = [characters subarrayWithRange:range];

NSString *truncated = [NSString stringWithFormat:@"%@...", [truncatedCharacters componentsJoinedByString:@" "]];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!