Last active
December 11, 2015 09:12
-
-
Save ryuheechul/0b1188e29fa36855348f to your computer and use it in GitHub Desktop.
To get all ranges of the string in NSString
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// NSString+Ranges.h | |
// Modeling | |
// | |
// Created by Heechul Ryu on 12/11/15. | |
// Copyright © 2015 Heechul Ryu. All rights reserved. | |
// | |
#import <Foundation/Foundation.h> | |
@interface NSString (Ranges) | |
- (nonnull NSArray <NSValue *> *)rangesOfString:(nonnull NSString *)string; | |
@end | |
// | |
// NSString+Ranges.m | |
// Modeling | |
// | |
// Created by Heechul Ryu on 12/11/15. | |
// Copyright © 2015 Heechul Ryu. All rights reserved. | |
// | |
#import "NSString+Ranges.h" | |
@implementation NSString (Ranges) | |
- (NSArray <NSValue *> *)rangesOfString:(NSString *)string | |
{ | |
NSMutableArray *ranges = [NSMutableArray new]; | |
NSString *searchedString = @""; | |
NSString *toBeSearchedString = self; | |
while (toBeSearchedString.length) { | |
NSRange range = [toBeSearchedString rangeOfString:string]; | |
if (range.location == NSNotFound) { | |
break; | |
} | |
NSRange rangeInTotal = NSMakeRange(range.location + searchedString.length, range.length); | |
NSString *justSearchedString = [toBeSearchedString substringToIndex:range.location + range.length]; | |
toBeSearchedString = [toBeSearchedString substringFromIndex:justSearchedString.length]; | |
searchedString = [NSString stringWithFormat:@"%@%@", searchedString, justSearchedString]; | |
[ranges addObject:[NSValue valueWithRange:rangeInTotal]]; | |
} | |
return ranges; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment