2010-04-28 19 views
0

我試圖編寫一個方法,將從URI字符串中提取ID。我的下面的代碼似乎效率低下,什麼會是一個更好的方式找到id字符串?iPhone SDK inString函數

NSString *aID = [[[NSString alloc] initWithString:@"http://www.example.com/id368907840?mt=8&uo=4"] autorelease]; 
NSArray *arrStr = [aID componentsSeparatedByString:@"/id"]; 
aID = [arrStr objectAtIndex:1]; 
arrStr = [aID componentsSeparatedByString:@"?mt="]; 
aID = [arrStr objectAtIndex:0]; 

上面的給我留下了的NSString = 368907840

回答

3

您可以使用NSURL-lastPathComponentNSString-stringByTrimmingCharactersInSetNSCharacterSet+letterCharacterSet來完成同樣的任務,如下面的例子:

NSURL* url = [NSURL URLWithString:@"http://www.example.com/id368907840?mt=8&uo=4"]; 
NSString* lastpath = [url lastPathComponent]; // "id368907840" 
NSCharacterSet* letters = [NSCharacterSet letterCharacterSet]; 
NSString* result = [lastpath stringByTrimmingCharactersInSet:letters]; // 368907840 

免責聲明:我沒有真正嘗試過,所以你需要自己嘗試,但我相信這應該工作。

+0

謝謝我結合這個: lastpath = [lastpath substringFromIndex:2]; //「368907840」 – Skeep 2010-04-28 13:19:02

0

你可以使用subStringWithRange和rangeOfString,沿

NSString *aID = [[[NSString alloc] initWithString:@"http://www.example.com/id368907840?mt=8&uo=4"] autorelease]; 

int startIndex = [aID rangeOfString:@"id"].location + 2; 
int length = [aID rangeOfString:@"mt"].location - startIndex - 1; 

aID = [aID substringWithRange:NSMakeRange(startIndex, length)]; 
0

使用正則表達式的東西線的組合。其中一種情況是使用它們更容易,更易讀。

+0

我覺得可可沒有正則表達式嗎? – Skeep 2010-04-28 19:10:18

+0

請嘗試http://regexkit.sourceforge.net/RegexKitLite/index.html – 2010-04-29 03:29:52