Skip to content

Instantly share code, notes, and snippets.

@ryuheechul
Last active December 11, 2015 09:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryuheechul/0b1188e29fa36855348f to your computer and use it in GitHub Desktop.
Save ryuheechul/0b1188e29fa36855348f to your computer and use it in GitHub Desktop.
To get all ranges of the string in NSString
//
// 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