给NSString写个分类
扫描字符串中的连续数字。每扫描完成一段数字,就回调一次。
@interface NSString (JXScanConsecutiveNumber)
- (void)jx_scanConsecutiveNumberWithCallback:(void (^)(NSString *numberString, NSRange range, BOOL isLast, BOOL *stop))callback;
@end
用法
分别测试字母和数字混合与不混合的几种情况
NSString *string = @"Hello132634523-345336World65434223";
NSLog(@"----- %@ -----", string);
[string jx_scanConsecutiveNumberWithCallback:^(NSString *numberString, NSRange range, BOOL isLast, BOOL *stop) {
NSLog(@"number:%@, range:%@, isLast:%@", numberString, NSStringFromRange(range), isLast ? @"YES" : @"NO");
}];
// test2
string = @"hello88kkk666ooo";
NSLog(@"----- %@ -----", string);
[string jx_scanConsecutiveNumberWithCallback:^(NSString *numberString, NSRange range, BOOL isLast, BOOL *stop) {
NSLog(@"number:%@, range:%@, isLast:%@", numberString, NSStringFromRange(range), isLast ? @"YES" : @"NO");
if ([numberString isEqualToString:@"88"]) {
// 中断扫描
*stop = YES;
NSLog(@"中断扫描");
}
}];
// test3
string = @"834053450";
NSLog(@"----- %@ -----", string);
[string jx_scanConsecutiveNumberWithCallback:^(NSString *numberString, NSRange range, BOOL isLast, BOOL *stop) {
NSLog(@"number:%@, range:%@, isLast:%@", numberString, NSStringFromRange(range), isLast ? @"YES" : @"NO");
}];
// test4
string = @"12345Hello";
NSLog(@"----- %@ -----", string);
[string jx_scanConsecutiveNumberWithCallback:^(NSString *numberString, NSRange range, BOOL isLast, BOOL *stop) {
NSLog(@"number:%@, range:%@, isLast:%@", numberString, NSStringFromRange(range), isLast ? @"YES" : @"NO");
}];
输出
----- Hello132634523-345336World65434223 -----
number:132634523, range:{5, 9}, isLast:NO
number:345336, range:{15, 6}, isLast:NO
number:65434223, range:{26, 8}, isLast:YES
----- hello88kkk666ooo -----
number:88, range:{5, 2}, isLast:NO
中断扫描
----- 834053450 -----
number:834053450, range:{0, 9}, isLast:YES
----- 12345Hello -----
number:12345, range:{0, 5}, isLast:NO
网友评论