开发者

multiple String Replaces in Objective C

I know this is th开发者_运维问答e 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"??


-stringByReplacingOccurrencesOfString: returns a new string. The original string terms won't be affected by this function. 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. (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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜