I'm looking for a way to replace a character at a certain index of a NSString.
For example: myString = @"******";
I want to replace the 3rd " * " with an "A", so that the string looks like this: myString = @"**A***";
How can I achieve this?
Thanks in advance
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
If you don't mind using a little C, use something like this:
char *str = (char *)[myString UTF8String];
str[2] = 'A';
myString = [NSString stringWithUTF8String:str];
Of course you should be absolutely sure that myString has at least 3 characters before doing this. Other than that, it's a very fast and efficient way to do something like this.
My contribution with a swift extension from the response :
extension NSString{
func replacingACharacterAtIndex(pIndex : Int, pChar : Character) -> NSString{
return self.stringByReplacingCharactersInRange(NSRange(location: pIndex, length: 1), withString: String(pChar))
}
}