用其他多个字符替换nsstring中的多个字符

时间:2015-02-10 05:54:48

标签: objective-c nsstring

用其他多个字符替换nsstring中的多个字符?

NSString *jobs = @"The designs of the iPhone 6 and iPhone 6 Plus were influenced by that of the iPad Air, with a glass front that is curved around the edges of the display,and an aluminum rear that contains two plastic strips for the antenna; both models come in gold, silver, and space gray finishes";


NSString * jobs2 = [jobs stringByReplacingOccurrencesOfString:@" "withString:@"_"];

NSLog(@" string is %@ ",jobs2);

它将空间("")替换为" - "

但我希望用@替换              换成$              h替换为#,,等等

全部在单一功能中 用其他多个字符替换nsstring中的多个字符?

2 个答案:

答案 0 :(得分:0)

写一个包含替换字符的字典并编写自己的函数来迭代字符替换(然后将其包装在NSString类别中)或者枚举并替换它们。

请参阅此帖子:https://stackoverflow.com/a/19314718/874585

答案 1 :(得分:0)

此方法接受字符串和字典。字符串是您要在其中替换各种字符的原始字符串,第二个字符串是一个字典,其中包含要替换为键的字符以及要作为值插入的新字符。

- (NSString *)replaceSubstringsIn:(NSString *)string with:(NSDictionary *)replacements {

    NSString *result = string;

    for (NSString *key in replacements) {
        result = [result stringByReplacingOccurrencesOfString:key
                                                   withString:replacements[key]];
    }

    return result;
}

你可以这样称呼它

NSDictionary *dictionary = @{ @" " : @"-", @"some" : @"any"};
NSString *string = @"some to any";

NSLog(@"%@", [self replaceSubstringsIn:string with:dictionary]);