2012-08-14 47 views
0

我有這樣的字符串:如何獲取字符串的特定部分?

"This is test string http://www.google.com and it is working." 

我想只有從上面的字符串的鏈接(http://www.google.com)。我怎麼才能得到它?

+0

之間有什麼區別 'http://www.google.com' 和 'http://www.google.com' ?你已經發布了相同的字符串.... – 2012-08-14 07:14:49

+0

和整個字符串在哪裏? – 2012-08-14 07:19:23

+0

「這是測試字符串http:www.google.com並且它正在工作」是一個完整的字符串 – Birju 2012-08-14 07:20:37

回答

0

這將工作就像一個魅力:

NSString *totalString = @"This is test string http://www.google.com and it is working."; 
NSLog(@"%@", totalString); 

NSRange urlStart = [totalString rangeOfString: @"http"]; 
NSRange urlEnd = [totalString rangeOfString: @".com"]; 
NSRange resultedMatch = NSMakeRange(urlStart.location, urlEnd.location - urlStart.location + urlEnd.length); 

NSString *linkString = [totalString substringWithRange:resultedMatch]; 

NSLog (@"%@", linkString); 
+1

Thnx我frnd它工作完美:-) – Birju 2012-08-14 07:41:29

+0

被感染!您的網址必須以「http」開頭並以「.com」結尾,如果以「.net」或「.info」或其他形式結尾,請編輯NSRange urlEnd。 – 2012-08-14 07:45:16

0

我不知道如果我正確地理解你的問題,但你應該看看正則表達式 ...

1

它應該是這樣的:

NSString *test = @"This is test string http://www.google.com and it is working."; 

NSString *string = [test stringByAppendingString:@" "]; 

NSError *error = NULL; 
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"https?://[^ ]* " 
                     options:0 
                     error:&error]; 
NSArray *matches = [regex matchesInString:string 
            options:0 
            range:NSMakeRange(0, [string length])]; 

for (NSTextCheckingResult *match in matches) { 
    NSRange matchRange = [match range]; 
    NSString *url = [string substringWithRange:matchRange]; 

    NSLog(@"Found URL: %@", url); 
} 

你可以找到了解使用NSRegularExpression進一步的信息:

https://developer.apple.com/library/mac/#documentation/Foundation/Reference/NSRegularExpression_Class/Reference/Reference.html

0

有一個看看NSString類的文檔 - 那裏有一堆方法來查找某些子字符串格式的位置,在delimeters上拆分字符串,並提取子字符串等。

在上面的例子中,如果你想提取任何嵌入的URL字符串中,你可以先分割字符串起來使用:

NSArray *substrings = [myString componentsSeparatedByString:@" "]; 

然後將得到的陣列中,環路通過它,看看它有一個「HTTP」字符串:

for (int i=0;i<[substrings length];i++) { 
    NSString aStr = [substrings objectAtIndex:i]; 
    if ([aStr rangeOfString:@"http"].location != NSNotFound) { 
     NSLog(@"I found a http url:%@", aStr); 
    } 
} 
+0

NSArray不支持長度 – Birju 2012-08-14 07:38:34

+0

[子字符串計數]你實際上是否自己寫過一行代碼? – gamozzii 2012-08-14 15:18:49

相關問題