递归搜寻NSString中重复的文本
效果
源码
https://github.com/YouXianMing/iOS-Project-Examples 中的 StringRange 项目
// // NSString+Range.h // NSString // // Created by YouXianMing on 16/5/22. // Copyright © 2016年 YouXianMing. All rights reserved. // #import <Foundation/Foundation.h> @interface NSString (Range) /** * Finds and returns the ranges of a given string, within the given range of the receiver. * * @param searchString searchString. * @param mask A mask specifying search options. The following options may be specified by combining them with the C bitwise OR operator: NSCaseInsensitiveSearch, NSLiteralSearch, NSBackwardsSearch, NSAnchoredSearch. See String Programming Guide for details on these options. * @param range serachRange. * * @return Ranges. */ - (NSArray <NSValue *> *)rangesOfString:(NSString *)searchString options:(NSStringCompareOptions)mask serachRange:(NSRange)range; @end
// // NSString+Range.m // NSString // // Created by YouXianMing on 16/5/22. // Copyright © 2016年 YouXianMing. All rights reserved. // #import "NSString+Range.h" @implementation NSString (Range) - (NSArray <NSValue *> *)rangesOfString:(NSString *)searchString options:(NSStringCompareOptions)mask serachRange:(NSRange)range { NSMutableArray *array = [NSMutableArray array]; [self rangeOfString:searchString range:NSMakeRange(0, self.length) array:array options:mask]; return array; } - (void)rangeOfString:(NSString *)searchString range:(NSRange)searchRange array:(NSMutableArray *)array options:(NSStringCompareOptions)mask { NSRange range = [self rangeOfString:searchString options:mask range:searchRange]; if (range.location != NSNotFound) { [array addObject:[NSValue valueWithRange:range]]; [self rangeOfString:searchString range:NSMakeRange(range.location + range.length, self.length - (range.location + range.length)) array:array options:mask]; } } @end