如何替换字符是一个字符串在Objective-C?
NSString对象是不可变的(它们不能被改变),但是有一个可变的子类NSMutableString,它为你提供了几个替换字符串中的字符的方法。这可能是你最好的选择。
NSString
NSMutableString
你可以用这个方法
- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement
...获取一个替换了子字符串的新字符串(其他请参阅NSString文档)
示例使用
NSString *str = @"This is a string"; str = [str stringByReplacingOccurrencesOfString:@"string" withString:@"duck"];
iOS旧版本存在此问题。在最新的研究中,从右到左的方法效果很好。 我所做的是:
首先我查看iOS版本:
if (![self compareCurVersionTo:4 minor:3 point:0])
比:
// set RTL on the start on each line (except the first) myUITextView.text = [myUITextView.text stringByReplacingOccurrencesOfString:@"\n" withString:@"\u202B\n"];
如果你想替换多个字符串:
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
NSString *stringreplace=[yourString stringByReplacingOccurrencesOfString:@"search" withString:@"new_string"];