简体   繁体   English

Objective C中的多个String替换

[英]multiple String Replaces in Objective C

I know this is the wrong way to do it (because it errors) but you can see what i'm trying to do: 我知道这是错误的做法(因为它错误),但你可以看到我正在尝试做什么:

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:@""];

I have a search term called "terms" and want to output a cleaned up version into "urlTerm"?? 我有一个名为“条款”的搜索词,想要将清理后的版本输出到“urlTerm”中?

-stringByReplacingOccurrencesOfString: returns a new string . -stringByReplacingOccurrencesOfString:返回一个新字符串 The original string terms won't be affected by this function. 原始字符串terms不受此功能的影响。 Even if terms will be affected, the 2nd statement will never succeed because all spaces has become + already in the 1st statement, and no double spaces are left. 即使terms受到影响,第二个语句也永远不会成功,因为所有空格已经在第一个语句中已经+ ,并且没有剩余双空格。 (OK it turns out that "double space" is a tab. :| ) (好的,事实证明“双倍空间”是一个标签。:|)

You could use 你可以用

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:@"+"];
NSString *urlTerm = [terms stringByTrimmingCharactersInSet:
[NSCharacterSet characterSetWithCharactersInString:@"\t&'-_"]];
urlTerm = [urlTerm stringByReplacingOccurrencesOfString:@" " withString:@"+"];
NSString *urlTerm = [terms stringByReplacingOccurrencesOfString:@" " withString:@"+"];
urlTerm = [urlTerm stringByReplacingOccurrencesOfString:@"  " withString:@""];

etc. 等等

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM