benhowdle89
benhowdle89

Reputation: 37504

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"??

Upvotes: 2

Views: 2840

Answers (3)

NSGod
NSGod

Reputation: 22968

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

Upvotes: 4

kennytm
kennytm

Reputation: 523754

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

Upvotes: 4

Aleks N.
Aleks N.

Reputation: 6247

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

etc.

Upvotes: 1

Related Questions