Replacing one character in a string in Objective-C

2019-01-07 17:49发布

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?

4条回答
淡お忘
2楼-- · 2019-01-07 17:59

Here is the code:

[aString stringByReplacingCharactersInRange:NSMakeRange(3,1) withString:@"B"];
查看更多
在下西门庆
3楼-- · 2019-01-07 18:13

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"

查看更多
我命由我不由天
4楼-- · 2019-01-07 18:16

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

查看更多
冷血范
5楼-- · 2019-01-07 18:24
NSString *str = @"123*abc";
str = [str stringByReplacingOccurrencesOfString:@"*" withString:@""];
//str now 123abc
查看更多
登录 后发表回答