Sunday, May 19, 2013

NSString stringByReplacingCharactersInRange example ios


stringByReplacingCharactersInRange: withString:

Returns a new string in which the characters in a specified range of the receiver are replaced by a given string.
- (NSString *)stringByReplacingCharactersInRange:(NSRange)rangewithString:(NSString *)replacement
Parameters
range
A range of characters in the receiver.
replacement
The string with which to replace the characters in range.
Return Value of [NSString stringByReplacingCharactersInRange]
A new string in which the characters in range of the receiver are replaced byreplacement.
Example of [NSString stringByReplacingCharactersInRange]
NSString *someText = @"Goat";
NSRange range = NSMakeRange(0,1);
NSString *newText = [someText stringByReplacingCharactersInRange:range withString:@"B"];
Example of [NSString stringByReplacingCharactersInRange]
NSString *myword=[NSString stringWithString:@"0123456789"];

NSLog(@"Before = %@ ",myword);

NSRange firstCharRange = NSMakeRange(1,2); 
// Frist argument is start point and second is end point it's star from 0 and so on.
myword = [myword stringByReplacingCharactersInRange:firstCharRange withString:@"H"];

NSLog(@"After = %@ ",myword);
Example of [NSString stringByReplacingCharactersInRange]
NSString *theRiddle;
NSString *hiddenTextField = [[[NSMutableString alloc] initWithString:hiddenText.text] autorelease];
for (int i = textCount-1 ; i>=0; i--) {
    NSString *aChar=[fullTextField substringWithRange:NSMakeRange(i,1)];
    if ([aChar isEqualToString:@" "]) {
        theRiddle= [hiddenTextField stringByReplacingCharactersInRange:NSMakeRange(i, 1) withString:@" "];
    }else if ([aChar isEqualToString:character]) {
        theRiddle =[hiddenTextField stringByReplacingCharactersInRange:NSMakeRange(i, 1) withString:aChar];
    }
    else {
        theRiddle = hiddenTextField;
    }
    hiddenTextField = theRiddle;    
}
hiddenText.text=theRiddle;