Sunday, May 19, 2013

NSString stringByReplacingOccurrencesOfString example ios


stringByReplacingOccurrencesOfString: withString:

Returns a new string in which all occurrences of a target string in the receiver are replaced by another given string.
- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement
Parameters
target
The string to replace.
replacement
The string with which to replace target.
Return Value of [NSString stringByReplacingOccurrencesOfString]
A new string in which all occurrences of target in the receiver are replaced byreplacement.
Discussion
InvokesstringByReplacingOccurrencesOfString:withString:options:range:with0 options and range of the whole string.
Example of [NSString stringByReplacingOccurrencesOfString]
NSString *string1 = "Hello WORLD12";
NSString *string2 = "world";
NSRange *range = [string1 rangeOfString:string2];
if (range.length > 0){
    NSString *newString = [string1 substringFromIndex:range.location+6];
    [string1 stringByReplacingOccurrencesOfString:newString withString:string2];
}
Example of [NSString stringByReplacingOccurrencesOfString]
NSString *bump5 = [bump3 stringByReplacingOccurrencesOfString:@"[\\\"" withString:@""];
Example of [NSString stringByReplacingOccurrencesOfString]
    NSString  * str_aLine;
    str_aLine = @"sometext \n and \t     and on";
    // replace tabs to space
    str_aLine = [str_aLine stringByReplacingOccurrencesOfString:@"\t" withString:@" "];
    // replace \n to space
    str_aLine = [str_aLine stringByReplacingOccurrencesOfString:@"\n" withString:@" "];
    // replace \r to space
    str_aLine = [str_aLine stringByReplacingOccurrencesOfString:@"\r" withString:@" "];
    // reduce spaces to one space
    str_aLine = [str_aLine stringByReplacingOccurrencesOfString:@" +" withString:@" " options:NSRegularExpressionSearch range:NSMakeRange(0, str_aLine.length)];
    // trim begin and end from white spaces
    str_aLine = [str_aLine stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];