ios开发之--NSString中substringFromIndex,substringWithRange,substringToIndex方法的使用

时间:2021-06-25 15:56:35

1,substringFromIndex

从索引0开发到到index的后面的字符

2,substringWithRange

取指定range里面的字符,左边为索引index,右边为截取的范围

3,substringToIndex

从索引0到给定的索引index

代码如下:

NSString *str = @"";
// NSString *subString0 = [str substringFromIndex:-1];   //会放生越界错误

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

NSString *subString2 = [str substringFromIndex:];       //@"2345"

NSString *subString3 = [str substringFromIndex:];       //@"5"

NSString *subString4 = [str substringFromIndex:];       //@""

// NSString *subString5 = [str substringFromIndex:6];   //会放生越界错误
// NSString *subString10 = [str substringToIndex:-1];    //会放生越界错误

NSString *subString11 = [str substringToIndex:];         //@"“

NSString *subString12 = [str substringToIndex:];         //@"1”

NSString *subString13 = [str substringToIndex:];         //@"1234“

NSString *subString14 = [str substringToIndex:];         //@"12345”

// NSString *subString15 = [str substringToIndex:6];     //会放生越界错误
NSRange range1 = NSMakeRange(-, );

NSRange range2 = NSMakeRange(, );

NSRange range3 = NSMakeRange(, );

NSRange range4 = NSMakeRange(, );

NSRange range5 = NSMakeRange(, );

NSRange range6 = NSMakeRange(, );
//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”