Objective C中的多个String替换

时间:2010-11-15 08:16:38

标签: iphone objective-c string

我知道这是错误的做法(因为它有错误),但你可以看到我正在尝试做的事情:

NSString *urlTerm = [terms stringByReplacingOccurrencesOfString:@" " withString:@"+"];
NSString *urlTerm = [terms stringByReplacingOccurrencesOfString:@"  " withString:@""];
NSString *urlTerm = [terms stringByReplacingOccurrencesOfString:@"&" withString:@""];
NSString *urlTerm = [terms stringByReplacingOccurrencesOfString:@"'" withString:@""];
NSString *urlTerm = [terms stringByReplacingOccurrencesOfString:@"-" withString:@""];
NSString *urlTerm = [terms stringByReplacingOccurrencesOfString:@"_" withString:@""];

我有一个名为“条款”的搜索字词,想要将已清理的版本输出到“urlTerm”??

3 个答案:

答案 0 :(得分:4)

-stringByReplacingOccurrencesOfString:会返回新字符串。原始字符串terms不受此功能的影响。 即使terms受到影响,第二个语句也永远不会成功,因为第一个语句中的所有空格已经变为+,并且没有留下双空格。(好吧)事实证明“双空格”是一个标签。:|)

您可以使用

NSString* urlTerm = terms;
urlTerm = [urlTerm stringByReplacingOccurrencesOfString:@"\t" withString:@""];
urlTerm = [urlTerm stringByReplacingOccurrencesOfString:@"&" withString:@""];
urlTerm = [urlTerm stringByReplacingOccurrencesOfString:@"'" withString:@""];
urlTerm = [urlTerm stringByReplacingOccurrencesOfString:@"-" withString:@""];
urlTerm = [urlTerm stringByReplacingOccurrencesOfString:@"_" withString:@""];
urlTerm = [urlTerm stringByReplacingOccurrencesOfString:@" " withString:@"+"];

答案 1 :(得分:4)

NSString *urlTerm = [terms stringByTrimmingCharactersInSet:
[NSCharacterSet characterSetWithCharactersInString:@"\t&'-_"]];
urlTerm = [urlTerm stringByReplacingOccurrencesOfString:@" " withString:@"+"];

答案 2 :(得分:1)

NSString *urlTerm = [terms stringByReplacingOccurrencesOfString:@" " withString:@"+"];
urlTerm = [urlTerm stringByReplacingOccurrencesOfString:@"  " withString:@""];