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"
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"
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];
NSString *foo = @"ABCD 1234 ABCD TEST";
NSLog(@"Actual string: %@",foo);
int location = [foo rangeOfString:@"1234"].location; //location of 1234
NSRange range = NSMakeRange(location, (foo.length)-location); //create range
foo = [foo stringByReplacingOccurrencesOfString:@"ABCD" withString:@"foo" options:NSLiteralSearch range:range]; //replacing ABCD with foo
NSLog(@"Updated string: %@",foo);
Actual string: ABCD 1234 ABCD TEST
Updated string: ABCD 1234 foo TEST
Here I'm searching 1234 within foo, then making NSRange for replacing occurance of ABCD after 1234 string.