52

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,833
  • 13
  • 59
  • 112
RanLearns
  • 4,086
  • 5
  • 44
  • 81

4 Answers4

94

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
  • 37,241
  • 25
  • 195
  • 267
theChrisKent
  • 15,029
  • 3
  • 61
  • 62
  • 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
32
NSString *str = @"123*abc";
str = [str stringByReplacingOccurrencesOfString:@"*" withString:@""];
//str now 123abc
MD SHAHIDUL ISLAM
  • 14,325
  • 6
  • 82
  • 89
7

Here is the code:

[aString stringByReplacingCharactersInRange:NSMakeRange(3,1) withString:@"B"];
Duncan Babbage
  • 19,972
  • 4
  • 56
  • 93
Zakaria
  • 14,892
  • 22
  • 84
  • 125
5

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

Luke
  • 11,426
  • 43
  • 60
  • 69
Bourne
  • 10,094
  • 5
  • 24
  • 51