NSString类中三个用于获取子字符串的方法:
NSString类中提供了这样三个方法用于获取子字符串:
它们该怎么使用呢?见下面代码即可知道。
NSString *str = @"12345";
-substringFromIndex: 以指定索引开始(包括指定索引的字符,索引从0开始),并包括之后的全部字符;
// 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]; //会放生越界错误
-substringToIndex: 从字符串的开头一直截取到指定的索引,但不包括该索引的字符(可以看作是从目标字符串开头截取索引个字符);
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]; //会放生越界错误
-substringWithRange: 按照所给出的索引(索引从0开始),长度(l),任意地从指定索引的字符处(包括该索引的字符)中截取l个字符
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"