Search code examples
objective-cxcode4

what is range in nsstring and how we pass values in it?


What is range in NSString? example when we use the following function-

replaceOccurrencesOfString:withString:options:range:

what should be passed in parameters?

scenario- find "aaa" in first half of a string and replace it with "bbb"


Solution

  • The range parameter is of type NSRange which consists of location and length. As the name implies it specifies the range of characters in the string that should be used in the method.

    Caveat: "Character" in this sense is really a Unicode UTF-16 "code fragment"—which is not what people commonly expect a character to be. So splitting a string in half could split in the middle of a surrogate pair, which renders the substrings invalid. To split at proper positions use rangeOfComposedCharacterSequencesForRange:.

    Here's a proper example:

    NSMutableString *myString = [@"有人给我们树立了炸弹" mutableCopy];
    NSRange range = {0, [myString length] / 2};
    range = [myString rangeOfComposedCharacterSequencesForRange:range];
    [myString replaceOccurrencesOfString:@"炸弹"
                              withString:@"💣"
                                 options:0
                                   range:range];