51

Hoping somebody can help me out - I would like to replace a certain character in a string and am wondering what is the best way to do this?

I know the location of the character, so for example, if I want to change the 3rd character in a string from A to B - how would I code that?

shkschneider
  • 17,185
  • 13
  • 56
  • 110
RanLearns
  • 3,946
  • 5
  • 42
  • 76

4 Answers4

91

If it is always the same character you can use:

stringByReplacingOccurrencesOfString:withString:

If it is the same string in the same location you can use:

stringByReplacingOccurrencesOfString:withString:options:range:

If is just a specific location you can use:

stringByReplacingCharactersInRange:withString:

Documentation here: https://developer.apple.com/documentation/foundation/nsstring

So for example:

NSString *someText = @"Goat";
NSRange range = NSMakeRange(0,1);
NSString *newText = [someText stringByReplacingCharactersInRange:range withString:@"B"];

newText would equal "Boat"

Cœur
  • 34,719
  • 24
  • 185
  • 251
theChrisKent
  • 14,981
  • 3
  • 59
  • 61
  • 6
    Thanks for adding the code example. For others who may be wondering, the '0' in NSMakeRange is the character's position, and the '1' is the length starting at character 0 that you wish to replace - so to replace the first character you do (0,1) to replace the third character you do (2,1) and so forth. Thanks!! – RanLearns Mar 07 '11 at 19:22
31
NSString *str = @"123*abc";
str = [str stringByReplacingOccurrencesOfString:@"*" withString:@""];
//str now 123abc
MaxEcho
  • 13,989
  • 6
  • 76
  • 86
7

Here is the code:

[aString stringByReplacingCharactersInRange:NSMakeRange(3,1) withString:@"B"];
Duncan Babbage
  • 19,469
  • 3
  • 52
  • 92
Zakaria
  • 14,664
  • 22
  • 83
  • 123
5

Use the replaceCharactersInRange: withString: message on a NSMutableString object.

Luke
  • 11,400
  • 43
  • 61
  • 68
Bourne
  • 9,700
  • 5
  • 23
  • 51