有三种方法:
- (NSString *)substringFromIndex:(NSUInteger)from;
- (NSString *)substringToIndex:(NSUInteger)to;
- (NSString *)substringWithRange:(NSRange)range; // Use with rangeOfComposedCharacterSequencesForRange: to avoid breaking up character sequences
解释:
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”
例子: 金融规范化金额 numbers= 1,000.00
NSString *string = [numbers substringToIndex:[numbers length]-3];//删除后三位 得到1000
NSString *string1 = [numbers substringFromIndex:numbers.length- 3];//得到后三位 得到.00
方法:
//字符串1000.00转化成1,000.00
- (NSString *)hanleNums:(NSString *)numbers{
NSString *string = [numbers substringToIndex:[numbers length]-3];//得到小数点之前的整数
NSString *str = [string substringWithRange:NSMakeRange(string.length%3, string.length-string.length%3)];
NSString *strs = [string substringWithRange:NSMakeRange(0, string.length%3)];
for (int i =0; i < str.length; i =i+3) {
NSString *sss = [str substringWithRange:NSMakeRange(i, 3)];
strs = [strs stringByAppendingString:[NSString stringWithFormat:@",%@",sss]];
}
if ([[strs substringWithRange:NSMakeRange(0, 1)] isEqualToString:@","]) {
strs = [strs substringWithRange:NSMakeRange(1, strs.length-1)];
}
NSString *string1 = [numbers substringFromIndex:numbers.length- 3];//得到小数点后两位
NSString * allStr = [NSString stringWithFormat:@"%@%@",strs,string1];
//得到完整的1,000.00
return allStr;
}