2015-02-10 132 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]);