Replacing one character in a string in Objective-C

Objective CIosStringNsstring

Objective C Problem Overview


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?

Objective C Solutions


Solution 1 - Objective C

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"

Solution 2 - Objective C

NSString *str = @"123*abc";
str = [str stringByReplacingOccurrencesOfString:@"*" withString:@""];
//str now 123abc

Solution 3 - Objective C

Here is the code:

[aString stringByReplacingCharactersInRange:NSMakeRange(3,1) withString:@"B"];

Solution 4 - Objective C

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRanLearnsView Question on Stackoverflow
Solution 1 - Objective CtheChrisKentView Answer on Stackoverflow
Solution 2 - Objective CMaxEchoView Answer on Stackoverflow
Solution 3 - Objective CZakariaView Answer on Stackoverflow
Solution 4 - Objective CBourneView Answer on Stackoverflow