如何替换字符是一个字符串在Objective-C?


当前回答

NSString *stringreplace=[yourString stringByReplacingOccurrencesOfString:@"search" withString:@"new_string"];

其他回答

该问题存在于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 *)stringByReplacingOccurrencesOfString:(NSString *)target 
                                        withString:(NSString *)replacement

...获取一个替换了子字符串的新字符串(其他请参阅NSString文档)

示例使用

NSString *str = @"This is a string";

str = [str stringByReplacingOccurrencesOfString:@"string"
                                     withString:@"duck"];
NSString *stringreplace=[yourString stringByReplacingOccurrencesOfString:@"search" withString:@"new_string"];

如果你想替换多个字符串:

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