Sunday, May 19, 2013

NSString stringByReplacingOccurrencesOfString withString example ios

[NSString 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
The string to replace.
The string with which to replace target.
Return Value of [NSString stringByReplacingOccurrencesOfString withString]
A new string in which all occurrences of target in the receiver are replaced byreplacement.
InvokesstringByReplacingOccurrencesOfString:withString:options:range:with0 options and range of the whole string.
[NSString stringByReplacingOccurrencesOfString withString] example
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];
[NSString stringByReplacingOccurrencesOfString withString] example
NSString *bump5 = [bump3 stringByReplacingOccurrencesOfString:@"[\\\"" withString:@""];
[NSString stringByReplacingOccurrencesOfString withString] example
    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]];