我有一个urlString:http://www.youtube.com/watch?v=5kdEhVtNFPo
我希望能够将其更改为:http://www.youtube.com/v/5kdEhVtNFPo
我该怎么做呢?我不确定是否应该使用实例方法substringWithRange:
或substringFromIndex:
我尝试了这个删除了第一部分,只留下了视频ID(它删除了http://www.youtube.com/watch?v=
)现在我只需要将http://www.youtube.com/v/
添加到字符串的开头。
NSString *newUrlString = [urlString substringFromIndex:31];
答案 0 :(得分:9)
NSString* newUrl = [oldUrl stringByReplacingOccurrencesOfString:@"watch?v=" withString:@"v/"];
请注意,只有在URL不包含字符串“watch?v =”的更多实例时,此方法才有效。
答案 1 :(得分:2)
我会提出一种不同的方式,可以对你提供的输入更灵活:
- (NSString) newURLStringForOldURLString:(NSString *)oldURLString
{
NSString *newURLString = nil;
NSURL *url = [[NSURL alloc] initWithString:oldURLString];
NSString *query = [url query]; /* v=5kdEhVtNFPo */
NSArray *fieldValuePairs = [query componentsSeparatedByString:@"&"];
for (NSString *pair in fieldValuePairs) {
NSArray *components = [pair componentsSeparatedByString:@"="];
NSString *field = [components objectAtIndex:0];
NSString *value = [components objectAtIndex:1];
if ([field isEqualToString:@"v"]) {
newURLString = [NSString stringWithFormat:@"%@://%@:%@/%@/%@", [url scheme], [url domain], [url port], field, value];
break;
}
}
[url release];
return newURLString;
}
答案 2 :(得分:0)
另一种选择:
NSString *str3 = @"http://www.youtube.com/watch?v=5kdEhVtNFPo";
NSString *outputString;
NSRange range = [str3 rangeOfString:@"watch?v="];
if(range.location != NSNotFound)
{
outputString = [str3 stringByReplacingCharactersInRange:range withString:@"v/"];
NSLog(@"%@",outputString);
}
答案 3 :(得分:0)
要足够灵活,您可以使用NSRegularExpression
:
NSString *str = @"http://www.youtube.com/watch?v=5kdEhVtNFPo";
NSString *pattern = @"((?:http:\\/\\/){0,1}www\\.youtube\\.com\\/)watch\\?v=([:alnum:]+)";
NSString *template = @"$1v/$2";
NSRegularExpression *regexp = [NSRegularExpression
regularExpressionWithPattern:pattern
options:NSRegularExpressionCaseInsensitive
error:nil];
NSString *newStr = [regexp stringByReplacingMatchesInString:str
options:0 range:NSMakeRange(0, [str length]) withTemplate:template];
NSLog(@"Replaced: %@", newStr);