Sunday, June 2, 2013

NSMutableString replaceOccurrencesOfString example in Objective C (iOS).

NSMutableString replaceOccurrencesOfString

Replaces all occurrences of a given string in a given range with another given string, returning the number of replacements.

- (NSUInteger)replaceOccurrencesOfString:(NSString *)target withString:(NSString *)replacement options:(NSStringCompareOptions)opts range:(NSRange)searchRange

The string to replace.
Important: Raises an NSInvalidArgumentException if target is nil.
The string with which to replace target.
Important: Raises an NSInvalidArgumentException if replacement is nil.[NSMutableString replaceOccurrencesOfString]
A mask specifying search options. See String Programming Guide for details.
If opts is NSBackwardsSearch, the search is done from the end of the range. If opts is NSAnchoredSearch, only anchored (but potentially multiple) instances are replaced. NSLiteralSearch and NSCaseInsensitiveSearch also apply.
The range of characters to replace. aRange must not exceed the bounds of the receiver. Specify searchRange as NSMakeRange(0, [receiver length]) to process the entire string.
Important: Raises an NSRangeException if any part of searchRange lies beyond the end of the receiver.

Return Value of [NSMutableString replaceOccurrencesOfString]
The number of replacements made.

Discussion of [NSMutableString replaceOccurrencesOfString]
This method treats the length of the string as a valid range value that returns an empty string.
NSMutableString replaceOccurrencesOfString example.
NSString *aString [ [[NSString alloc] initWithFormat:@"text %@ more text", self.strVariable];
[self.someMutableStringVar replaceOccurrencesOfString:@"replace" withString:aString options:NSCaseInsensitiveSearch range:NSMakeRange(0, [self.someMutableStringVar length])];
[aString release];

-(void)DoStuff2:(NSString *)aString
[self.someMutableStringVar appendString:aString];

Example of [NSMutableString replaceOccurrencesOfString].
NSMutableString * theMutableString = [[NSMutableString alloc] initWithString:@"\"Hello World!\""];

[theMutableString replaceOccurrencesOfString:@"\"" withString:@"" options:NSCaseInsensitiveSearch range:(NSRange){0,[theMutableString length]}];


[theMutableString release];

NSMutableString replaceOccurrencesOfString example.
 (NSMutableString *)fixLinkedFiledPath:(NSString *)aPath {
        NSMutableString *fixedPathOfFile = [NSMutableString stringWithString:aPath];
        NSString *dataFolderPath = [[NSApp delegate] dataFolderPath];
   [fixedPathOfFile replaceOccurrencesOfString:@"[Data Folder]" withString:dataFolderPath options:NSLiteralSearch range:NSMakeRange(0,[fixedPathOfFile length])];
NSString *pathURL = [self fixLinkedFiledPath:[link valueForKey:@"url"]];  //Somewhere in your code

End of NSMutableString replaceOccurrencesOfString example article.