2015-02-10 92 views
0

将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中的多个字符替换为其他多个字符?

+0

您可以编写自己的类别,这 – 2015-02-10 06:00:06

+0

我不知道,弄不明白,请帮我 – appintosh 2015-02-10 06:28:42

+0

谷歌什么的obj C三类是..你可以写你的自己的方法来实现你想要的,并使它成为使用类别的NSString类的一部分。 – 2015-02-10 06:51:34

回答

0

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

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

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]);