嗨獲取最後一個路徑部分我想要提取的最後一部分,從字符串,它是一個四位數字「03276」 I:E http://www.abc.com/news/read/welcome-new-gig/03276
從NSString的
我怎麼能做到這一點。
嗨獲取最後一個路徑部分我想要提取的最後一部分,從字符串,它是一個四位數字「03276」 I:E http://www.abc.com/news/read/welcome-new-gig/03276
從NSString的
我怎麼能做到這一點。
您還可以使用
NSString *sub = [@"http://www.abc.com/news/read/welcome-new-gig/03276" lastPathComponent];
試試這個:
NSString *myUrl = @"http://www.abc.com/news/read/welcome-new-gig/03276";
NSString *number = [[myUrl componentsSeparatedByString:@"/"] objectAtIndex: 5];
通過使用objectAtIndex:5您是確保它只能在特定的地址,如果地址更改爲類似http://www.abc.com/news/read/welcome-new-gig/ SOMETHING/03276,它打破了它。 – EmilioPelaez
如果你知道你有多少個字符需要,你可以做這樣的事情:
NSString *string = @"http://www.abc.com/news/read/welcome-new-gig/03276";
NSString *subString = [string substringFromIndex:[string length] - 5];
如果你只知道它的部分的最後斜線後,你可以這樣做:
NSString *string = @"http://www.abc.com/news/read/welcome-new-gig/03276";
NSString *subString = [[string componentsSeparatedByString:@"/"] lastObject];
如果你知道數字的長度,它不會改變,它可以是一樣簡單:
NSString *result = [string substringFromIndex:[string length] - 4];
NSString *str = @"http://www.abc.com/news/read/welcome-new-gig/03276";
NSArray *arr = [str componentSeparatedBy:@"gig/"];
NSString *strSubStringDigNum = [arr objectAtIndex:1];
strSubStringDigNum將具有值03276
如果字符串的最後部分始終是相同的長度(5個字符)您可以使用此方法提取最後一部分:
- (NSString *)substringFromIndex:(NSUInteger)anIndex
使用字符串的長度來確定開始索引。
事情是這樣的:
NSString *inputStr = @"http://www.abc.com/news/read/welcome-new-gig/03276";
NSString *newStr = [inputStr substringFromIndex:[inputStr length]-5];
NSLog(@"These are the last five characters of the string: %@", newStr);
(代碼未測試)
由於* nix中使用相同的路徑分隔符爲URL的,這將是有效的爲好。
[@"http://www.abc.com/news/read/welcome-new-gig/03276" lastPathComponent]
最後一個有用的字符串函數! – Burf2000
hi @Pierre,你爲什麼使用'lastPathComponent'?這是什麼意思? – Adela
@Adela我使用它,因爲它是NSString的一種方法,完全符合要求。當然,使用API提供的方法比編寫自己的邏輯更容易。並且意味着名字所說的。它會返回路徑的最後一個組件。查看https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/#//apple_ref/occ/instp/NSString/lastPathComponent查看字符串的一些示例並返回值。 – Pierre