递归搜寻NSString中重复的文本

Posted YouXianMing

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了递归搜寻NSString中重复的文本相关的知识,希望对你有一定的参考价值。

递归搜寻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

 

以上是关于递归搜寻NSString中重复的文本的主要内容,如果未能解决你的问题,请参考以下文章

匹配 NSString 和 UILabel 的文本 [重复]

JavaScript 代码片段

Shell – Grep 常见用法

48个值得掌握的JavaScript代码片段(上)

Java基础之方法的调用重载以及简单的递归

JavaSE 方法的使用