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

后端 未结 2 1908
梦如初夏
梦如初夏 2020-12-16 18:28

\"The

How can I truncate a string at a given length without annihilating a unicode character that mig

相关标签:
2条回答
  • 2020-12-16 19:21

    "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:@" "]];
    
    0 讨论(0)
  • 2020-12-16 19:22

    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 =  @"                                                                    
    0 讨论(0)
提交回复
热议问题