2010-09-03 22 views
13
NSString *url = @"http://stackoverflow.com/questions/ask"; 

如何獲取第4個「/」的字符位置?NSString字符位置

+0

你的意思是第4個「/」,第4個字符不是「/」。或者如果你的意思是所有「/」中的第四個「/」,對應於最後一個「/ ask」 – vodkhang 2010-09-03 02:22:15

+0

是最後一個「/ ask」 – Fasid 2010-09-03 02:28:36

回答

29

如果你只是想獲得的URL的最後一部分,你應該能夠使用此:

NSArray* items = [url componentsSeparatedByString:@"/"]; 

爲了得到最後的 '/' 字符的索引:

NSRange range = [url rangeOfString:@"/" options:NSBackwardsSearch]; 

從索引值range.location

要找到URL中的第四個「/」字符的索引:

int count = 0; 
int index = -1; 
for (unsigned int i=0; i < [url length]; ++i) { 
    if ([url characterAtIndex:i] == '/') { 
     ++count; 
     if (count == 4) { 
      index = i; 
      break; 
     } 
    } 
} 
+0

我需要索引但是thx – Fasid 2010-09-03 02:53:31

+0

它並不總是最後一個一個,它是第四個 – Fasid 2010-09-03 03:13:54

0

我在理解你的問題後編輯了我的答案。

亞太區首席技術官Matt的答案几乎是正確的,你只需要做一點點

NSArray* items = [url componentsSeparatedByString:@"/"]; 

if ([items count] > 4) { 
    NSString *string = [items objectAtIndex:4]; 
} 
7

通常你不必把信/索引。您只需使用NSURL中定義的許多便利方法,請參閱this Apple reference。我會做

NSURL* url=[NSURL URLWithString:@"http://stackoverflow.com/questions/ask"]; 
    NSString* last=[url lastPathComponent]; // last is now @"ask" 
5

另一種方式,可以使用

[url rangeOfString:@"/" options:NSBackwardsSearch].location 

希望它能幫助!

+0

我只是想弄清楚如何在一個字符串上手動執行「邏輯」換行符(即在空格處打斷)以在多個CCLabelTTF塊中吐出一個字符串,這正是我所需要的,謝謝! – redux 2013-10-23 07:30:40

+0

這應該被接受的答案... – 2016-02-03 09:20:30