截取字符串
我们有时候需要从一个字符串中截取子字符串,下面提供一下截取两个关键字之间的字符串的方法,
例如我们需从http://test.com?name=123&gender=0种截取name字段所对应的值"123"。
-(NSString *)getInterceptStringWithString:(NSString *)urlStr Key1:(NSString *)key1 key2:(NSString *)key2 { NSRange range = [urlStr rangeOfString:key1];//匹配得到的下标 NSLog(@"rang:%@",NSStringFromRange(range)); if (key2 != nil) { NSRange range1 = [urlStr rangeOfString:key2]; urlStr = [urlStr substringToIndex:range1.location]; } DBG_LOG(@"urlStr:%@", urlStr); NSString *interceptString = [urlStr substringFromIndex:range.location+range.length];//截取范围类的字符串 NSLog(@"截取的值为:%@",interceptString); return interceptString; }
调用:
NSString *interceptString = [self getInterceptStringWithString:urlStr Key1:@"name=" key2:@"&gender"];
得到的interceptString即为结果。