2010-10-01 53 views
0
@"/News/some news text/" 
@"/News/some other news text/" 
@"/About/Some about text/" 
@"/Abcdefg/Some abcdefg text/some more abcdefg text" 

如何剪出字符串的第一部分,以便最終得到以下字符串?如何刪除NSString的部分?

@"/News/" 
@"/News/" 
@"/About/" 
@"/Abcdefg/" 

回答

8

使用componentsSeparatedByString:分手字符串:

NSArray *components=[string componentsSeparatedByString:@"/"]; 
if ([components count]>=2) { 
    // Text after the first slash is second item in the array 
    return [NSString stringWithFormat:@"/%@/",[components objectAtIndex:1]]; 
} else { 
    return nil; // Up to you what happens in this situation 
} 
+0

謝謝你太多了! – Malene 2010-10-01 11:46:13

+1

@Malene:如果這個答案適合你,那麼請接受答案給予grahamparks適當的獎勵。 – 2010-10-01 13:20:43

+0

對不起 - 不知道。 。 。 -answer accepted ;-) – Malene 2010-10-21 14:55:18

2

如果這些路徑名,你可能要考慮的NSString的路徑相關的方法,如pathComponentspathByDeletingLastPathComponent

儘管路徑分隔符不太可能會發生變化,但不要依賴這些東西,並且使用專用的路徑操作方法而不是假設路徑分隔符將成爲某個特定字符是一種好習慣。

編輯從2013年開始:或者使用URL(更具體地說,NS/CFURL對象),蘋果已經非常明確地從現在起引用文件的正確方法,並且對於沙盒中的某些任務是必需的。