Sunday, May 19, 2013

NSString rangeOfComposedCharacterSequencesForRange example ios


[NSString rangeOfComposedCharacterSequencesForRange]

Returns the range in the string of the composed character sequences for a given range.
- (NSRange)rangeOfComposedCharacterSequencesForRange:(NSRange)range
Parameters
range
A range in the receiver. The range must not exceed the bounds of the receiver.
Return Value of [NSString rangeOfComposedCharacterSequencesForRange]
The range in the receiver that includes the composed character sequences in range.
Discussion
This method provides a convenient way to grow a range to include all composed character sequences it overlaps.
Example of [NSString rangeOfComposedCharacterSequencesForRange]
// define the range you're interested in
NSRange stringRange = {0, MIN([myString length], 20)};

// adjust the range to include dependent chars
stringRange = [myString rangeOfComposedCharacterSequencesForRange:stringRange];

// Now you can create the short string
NSString *shortString = [myString substringWithRange:stringRange];
Example of [NSString rangeOfComposedCharacterSequencesForRange]
NSMutableString *myString = [@"有人给我们树立了炸弹" mutableCopy];
NSRange range = {0, [myString length] / 2};
range = [myString rangeOfComposedCharacterSequencesForRange:range];
[myString replaceOccurrencesOfString:@"炸弹"
                          withString:@"💣"
                             options:0
                               range:range];
Example of [NSString rangeOfComposedCharacterSequencesForRange]
// cut a string by words
- (NSString *)stringCutByWordsToMaxLength:(int)length
{
     NSCharacterSet *whitespaceCharacterSet =
                      [NSCharacterSet whitespaceCharacterSet];

     // to consider: a range check on length here?
     NSRange relevantRange = NSMakeRange(0, length);

     // find beginning of last word
     NSRange lastWordRange =
           [self rangeOfCharacterFromSet:whitespaceCharacterSet
                  options:NSBackwardsSearch
                  range:relevantRange];

     if(lastWordRange.location == NSNotFound)
     {
          lastWordRange = relevantRange;
     }

    // adjust the range to include dependent chars
    stringRange = [self rangeOfComposedCharacterSequencesForRange:stringRange];

    // Now you can create the short string
    NSString *string = [self substringWithRange:stringRange];

    return [NSString stringWithFormat:@"%@...",string];
}