简体   繁体   中英

remove space from in between words and replace with '+'

NSString *locations=[[NSString alloc] init];
    locations=[mainView getLocationText];
    NSMutableArray *cs=[NSMutableArray arrayWithArray:[locations componentsSeparatedByString:@","]];
    NSString *city=[[cs objectAtIndex:0] replaceOccurrencesOfString:@" " withString:@"+" options:NSCaseInsensitiveSearch range:NSMakeRange(0,[[cs objectAtIndex:0] length])];
    NSString *state=[[cs objectAtIndex:1] replaceOccurrencesOfString:@" " withString:@"+" options:NSCaseInsensitiveSearch range:NSMakeRange(0,[[cs objectAtIndex:0] length])];
    NSMutableString *otherParams = [[[NSMutableString alloc] initWithFormat:@"city=%@&state=%@&beds=%@&baths=%@&minprice=%@&maxprice=%@&searchType=%@&page=1",city,state,bedsVal,bathsVal,minPriceVal,maxPriceVal,propTypeVal] autorelease];    

It gives the error:

Attempt to mutate immutable object with replaceOccurrencesOfString:withString:options:range:'

And spaces are not replaced with '+'

My Initial answer was incorrect , you should (as per Jasarien's answer) use stringByReplacingOccurrencesOfString:withString:options:range . rather than replaceOccurrencesOfString:withString:options:range

NSString is immutable. replaceOccurrencesOfString:withString:options:range: is only available on NSMutableString .

The method you should be using is:

stringByReplacingOccurrencesOfString:withString:options:range:

This is implemented on immutable strings, ie NSString and will return a new string with the replacements you specify.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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