2013-10-13 24 views
2

我在Objective-C中編寫代碼。我想從一個字符串中提取一個url。iOS rangeOfString找不到肯定存在的字符串

這裏是我的代碼:

NSMutableString *oneContent = [[latestPosts objectAtIndex:i] objectForKey:@"content"]; 
NSLog(@"%@", oneContent);//no problem 
NSString *string = @"http"; 
if ([oneContent rangeOfString:string].location == NSNotFound) { 
    NSLog(@"string does not contain substring"); 
} else { 
    NSLog(@"string contains substring!"); 
} 

正如你所看到的,我想提取從oneContent字符串的URL,我已經檢查了oneContent肯定包含「HTTP」,但爲什麼結果顯示沒有?

有一些更好的方法來提取網址是什麼?

+0

你可以嘗試這樣的[oneContent componentsSeparatedByString:@ 「stringtoseparate」。這將返回分隔的字符串 –

回答

0

檢查oneContent或您正在運行的實際代碼。

這工作:

NSMutableString *oneContent = [@"asdhttpqwe" mutableCopy]; 
NSLog(@"%@", oneContent);//no problem 
NSString *string = @"http"; 
if ([oneContent rangeOfString:string].location == NSNotFound) { 
    NSLog(@"string does not contain substring"); 
} else { 
    NSLog(@"string contains substring!"); 
} 

的NSLog輸出:

Untitled[5911:707] asdhttpqwe 
Untitled[5911:707] string contains substring! 

這可能是最好的使用可變的字符串,除非有一些實質性的理由這樣做。

我建議使用NSScanner。

+0

並以可能的情況下的比特更好地匹配的陣列,我試圖的NSMutableString * oneContent = [[NSString的stringWithFormat:@ 「H T噸號碼://thisisastring.com」] mutableCopy];並且這也起作用。 (我不得不添加空格,因爲SO正在將鏈接文本轉換爲鏈接。) – ericg

+0

謝謝,夥計。該字符串最初不是可變字符串,我根據教程進行了更改,但仍然無效。現在我擴展我的關鍵字,希望它更準確,它的工作原理!我不知道爲什麼,但是非常感謝。 – GraphicSound

相關問題