Replace a character at a certain index in NSString Replace a character at a certain index in NSString xcode xcode

Replace a character at a certain index in NSString


Try with this:

NSString *str = @"*******";str = [str stringByReplacingCharactersInRange:NSMakeRange(3, 1) withString:@"A"];NSLog(@"%@",str);


There are really two options;

Since NSString is read-only, you need to call mutableCopy on the NSString to get an NSMutableString that can actually be changed, then call replaceCharactersInRange:withString: on the NSMutableString to replace the characters in it. This is more efficient if you want to change the string more than once.

There is also a stringByReplacingCharactersInRange:withString: method on NSString that returns a new NSString with the characters replaced. This may be more efficient for a single change, but requires you to create a new NSString for each replacement.


Try this sample method

-(NSString *)string:(NSString*)string ByReplacingACharacterAtIndex:(int)i byCharacter:(NSString*)StringContainingAChar{    return [string stringByReplacingCharactersInRange:NSMakeRange(i, 1) withString:StringContainingAChar];}

if your string is "testing" and you want first character "t" should be replaced with "*" than call method

[self string:yourString ByReplacingACharacterAtIndex:0 byCharacter:@"*"]

Run and Go