19

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

niclas
  • 710
  • 1
  • 6
  • 17
  • 1
    Possible duplicate of http://stackoverflow.com/questions/7940104/replace-character-in-string – Emil Jan 21 '12 at 12:53
  • You can try with this link. It has the same problem that you are having. http://www.iphonedevsdk.com/forum/iphone-sdk-development/76235-nsstring-how-replace-character-certain-index.html – Yama Jan 21 '12 at 12:46

5 Answers5

32

Try with this:

NSString *str = @"*******";
str = [str stringByReplacingCharactersInRange:NSMakeRange(3, 1) withString:@"A"];
NSLog(@"%@",str);
Emil
  • 7,220
  • 17
  • 76
  • 135
aViNaSh
  • 1,318
  • 14
  • 15
18

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.

Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294
4

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

Liron Yahdav
  • 10,152
  • 8
  • 68
  • 104
Tunvir Rahman Tusher
  • 6,421
  • 2
  • 37
  • 32
1

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.

Mark
  • 689
  • 10
  • 17
0

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))
    }
}
Kevin ABRIOUX
  • 16,507
  • 12
  • 93
  • 99