检测URL字符串中的特定字符并将其替换为另一个字符

时间:2017-02-23 02:51:35

标签: objective-c nsstring

我将此URL字符串保存为NSString:

NSString *currentURL = self.webView.request.URL.absoluteString;

https://www.tripresso.com/cooperation/toyota?utm_source=cooperation&utm_medium=toyota&utm_campaign=toyota_app?dxid=7019b21e-bd3b-4bde-8917-f353149bdda4&appid=com.hotai.toyota.citydriver.official

正如您所看到的,此字符串中有2个?。我的问题是如何将第二个?替换为&

1 个答案:

答案 0 :(得分:0)

如果你想删除除第一次出现以外的所有内容,那么这应该有效:

NSString *currentURL = self.webView.request.URL.absoluteString;
NSMutableArray *components = [[currentURL componentsSeparatedByString:@"?"] mutableCopy];
NSString *firstComponent = [components firstObject];
[components removeObject:firstComponent];
NSString *newString = [NSString stringWithFormat:@"%@?%@", firstComponent, [components componentsJoinedByString:@"&"]];