1

我有一个 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];
4

4 回答 4

9
NSString* newUrl = [oldUrl stringByReplacingOccurrencesOfString:@"watch?v=" withString:@"v/"];

请注意,这仅在 URL 不包含字符串“watch?v=”的更多实例时才有效。

于 2012-10-12T12:16:53.063 回答
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;
}
于 2012-10-12T12:33:18.283 回答
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);

}
于 2012-10-12T12:26:01.997 回答
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);
于 2012-10-12T12:29:44.600 回答