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 (OK it turns out that "double space" is a tab. :| )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.
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.
精彩评论