Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

ios - Replacing one character in a string in Objective-C

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...