2011-12-29 31 views

回答

8

我不知道你到底是通过链接的意思,但如果你想你的NSString转换为NSURL比你可以做到以下几点:

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

编辑

这是怎么弄在给定的NSString所有网址:

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

有点冗长将其分割成一个数组然后搜索子字符串的范围,当你只能搜索子字符串的范围,只需一次。 – Abizern 2011-12-29 13:44:29

+1

@Abizern你引用的子字符串只适用于一种情况,也就是说如果字符串中只有一个URL,并且该URL是字符串中的最后一个对象,那么如果该URL将被隐藏在文本中间,它不适用于多个URL的 – Cyprian 2011-12-29 15:53:47

+0

是的,在他提出的扩展问题中,看起来您的解决方案似乎更符合法案。但是,基于块的枚举和检查[[arrString objectAtIndex:i] hasPrefix:@“http://”];可能会更高效一些。 – Abizern 2011-12-29 15:58:30

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和2将是:://stackoverflow.com/(我猜)

,那么你可以这样做:

NSString *u = [arrURL lastObject]; 

那么就喜欢:

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

相当漫长的,但我认为这会对你有用。希望能帮助你。

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]; 
} 
+0

感谢您的好评。我对此有更多疑问如何从本文获取链接“Stack over flow对于http://stackoverflow.com/ beginners”非常有用链接?谢谢。 – 2011-12-29 13:56:20

+0

这是一个完全不同的问题! – Abizern 2011-12-29 13:58:28

+0

谢谢。 Mr.Cyprian的回答对我来说非常好。谢谢你的努力。我再一次感谢你,并且我赞成你的回答。 – 2011-12-29 14:03:26