如何在iPhone中的NSString中查找并获取URL?

时间:2011-12-29 12:40:36

标签: iphone http url nsstring

我在NSString中有一个带有http://的文本。我想从NSString获取该http链接。如何从字符串中获取link / url?例如:'Stack over flow是初学者https://stackoverflow.com/'非常有用的链接。我想从文本中获取“https://stackoverflow.com/”。我怎样才能做到这一点?提前谢谢。

3 个答案:

答案 0 :(得分:8)

我不确定您的链接是什么意思,但如果您想将NSString转换为NSURL,则可以执行以下操作:

NSString *urlString = @"http://somepage.com";
NSURL *url = [NSURL URLWithString:urlString];

修改

这是如何获取给定NSString中的所有URL:

NSString *str = @"This is a grate website http://xxx.xxx/xxx you must check it out"; 

NSArray *arrString = [str componentsSeparatedByString:@" "];

for(int i=0; i<arrString.count;i++){
    if([[arrString objectAtIndex:i] rangeOfString:@"http://"].location != NSNotFound)
        NSLog(@"%@", [arrString objectAtIndex:i]);
}

答案 1 :(得分:4)

您可以直接搜索以@“http://”开头的子字符串,而不是将字符串拆分成数组并弄乱这种方式:

NSString *str = @"Stack over flow is very useful link for the beginners http://stackoverflow.com/";
// get the range of the substring starting with @"http://"
NSRange rng = [str rangeOfString:@"http://" options:NSCaseInsensitiveSearch];

// Set up the NSURL variable to hold the created URL
NSURL *newURL = nil;

// Make sure that we actually have found the substring
if (rng.location == NSNotFound) {
    NSLog(@"URL not found");
    // newURL is initialised to nil already so nothing more to do.
} else {
    // Get the substring from the start of the found substring to the end.
    NSString *urlString = [str substringFromIndex:rng.location];

    // Turn the string into an URL and put it into the declared variable
    newURL = [NSURL URLWithString:urlString];
}

答案 2 :(得分:1)

试试这个:

nsstring *str = @"Stack over flow is very useful link for the beginners http://stackoverflow.com/";

nsstring *http = @"http";
nsarray *arrURL = [str componentsSeparatedByString:@"http"];

这将在nsarray中提供两个对象。第一个对象将具有:Stack over flow is very useful link for the beginners,第二个将是:://stackoverflow.com/(我猜)

那么你可以这样做:

  NSString *u = [arrURL lastObject];

然后做:

nsstring *http = [http stringByAppendingFormat:@"%@",u];

相当冗长,但我认为这对你有用。希望对你有帮助。