2011-12-29 63 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