1. 程式人生 > >ios開發之--NSString中substringFromIndex,substringWithRange,substringToIndex方法的使用

ios開發之--NSString中substringFromIndex,substringWithRange,substringToIndex方法的使用

字符 nsrange min nbsp 範圍 clas ring div make

1,substringFromIndex

從索引0開發到到index的後面的字符

2,substringWithRange

取指定range裏面的字符,左邊為索引index,右邊為截取的範圍

3,substringToIndex

從索引0到給定的索引index

代碼如下:

NSString *str = @"12345";
// NSString *subString0 = [str substringFromIndex:-1];   //會放生越界錯誤

NSString *subString1 = [str substringFromIndex:0];       //@"12345"

NSString 
*subString2 = [str substringFromIndex:1]; //@"2345" NSString *subString3 = [str substringFromIndex:4]; //@"5" NSString *subString4 = [str substringFromIndex:5]; //@"" // NSString *subString5 = [str substringFromIndex:6]; //會放生越界錯誤
// NSString *subString10 = [str substringToIndex:-1];    
//會放生越界錯誤 NSString *subString11 = [str substringToIndex:0]; //@"“ NSString *subString12 = [str substringToIndex:1]; //@"1” NSString *subString13 = [str substringToIndex:4]; //@"1234“ NSString *subString14 = [str substringToIndex:5]; //@"12345” // NSString *subString15 = [str substringToIndex:6];
//會放生越界錯誤
NSRange range1 = NSMakeRange(-1, 5);

NSRange range2 = NSMakeRange(0, 6);

NSRange range3 = NSMakeRange(0, 5);

NSRange range4 = NSMakeRange(1, 4);

NSRange range5 = NSMakeRange(0, 0);

NSRange range6 = NSMakeRange(4, 1);
//NSString *subString31 = [str substringWithRange:range1]; //會放生越界錯誤

//NSString *subString32 = [str substringWithRange:range2]; //會放生越界錯誤

NSString *subString33 = [str substringWithRange:range3];   //@"12345“

NSString *subString34 = [str substringWithRange:range4];   //@"2345”

NSString *subString35 = [str substringWithRange:range5];   //@"”

NSString *subString36 = [str substringWithRange:range6];   //@"5”

ios開發之--NSString中substringFromIndex,substringWithRange,substringToIndex方法的使用