-4

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"

DD_
  • 7,230
  • 11
  • 38
  • 59
nitz19arg
  • 417
  • 7
  • 18
  • considered searching for description on developer.apple.com???? Try http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_DataTypes/Reference/reference.html – Baby Groot Feb 28 '13 at 06:58
  • [ReplaceOccurrencesOfStrin](http://cocoadev.com/wiki/ReplaceOccurrencesOfString) and also [NSRange](http://cocoadev.com/wiki/NSRange) – iPatel Feb 28 '13 at 07:07

2 Answers2

3

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];
Nikolai Ruhe
  • 81,520
  • 17
  • 180
  • 200
0
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.

Hemang
  • 26,840
  • 19
  • 119
  • 186