替换字符的最佳方法是使用Objective-C for iPhone SDK中的字符串?
你可以使用这个方法
- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement
...获取一个替换了子字符串的新字符串(参见NSString
其他文档)
使用示例
NSString *str = @"This is a string"; str = [str stringByReplacingOccurrencesOfString:@"string" withString:@"duck"];
NSString
对象是不可变的(它们不能被更改),但是有一个可变的子类NSMutableString
,它为您提供了几种替换字符串中字符的方法.这可能是你最好的选择.
如果您想要多个字符串替换:
NSString *s = @"foo/bar:baz.foo"; NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@"/:."]; s = [[s componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: @""]; NSLog(@"%@", s); // => foobarbazfoo
它还使用stringByReplacingCharactersInRange:withString替换字符串:
for (int i = 0; i < card.length - 4; i++) { if (![[card substringWithRange:NSMakeRange(i, 1)] isEqual:@" "]) { NSRange range = NSMakeRange(i, 1); card = [card stringByReplacingCharactersInRange:range withString:@"*"]; } } //out: **** **** **** 1234