これは私のソリューションです。基本的に、アルゴリズムは部分文字列の一致を探して文字列を走査し、その一致を配列に返します。
NSRangeは構造体であるため、配列に直接追加することはできません。 NSValueを使用すると、をにエンコードしてから配列に追加できます。範囲を取得するには、NSValueオブジェクトをNSRangeにデコードします。
#import <Foundation/Foundation.h>
NSRange makeRangeFromIndex(NSUInteger index, NSUInteger length) {
return NSMakeRange(index, length - index);
}
NSArray<NSValue *> * allLocationsOfStringMatchingSubstring(NSString *text, NSString *pattern) {
NSMutableArray *matchingRanges = [NSMutableArray new];
NSUInteger textLength = text.length;
NSRange match = makeRangeFromIndex(0, textLength);
while(match.location != NSNotFound) {
match = [text rangeOfString:pattern options:0L range:match];
if (match.location != NSNotFound) {
NSValue *value = [NSValue value:&match withObjCType:@encode(NSRange)];
[matchingRanges addObject:value];
match = makeRangeFromIndex(match.location + 1, textLength);
}
}
return [matchingRanges copy];
}
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSString *text = @"TATACCATGGGCCATCATCATCATCATCATCATCATCATCATCACAG";
NSString *pattern = @"CAT";
NSArray<NSValue *> *matches = allLocationsOfStringMatchingSubstring(text, pattern);
NSLog(@"Text: %@", text);
NSLog(@"Pattern: %@", pattern);
NSLog(@"Number of matches found: %li", matches.count);
[matches enumerateObjectsUsingBlock:^(NSValue *obj, NSUInteger idx, BOOL *stop) {
NSRange match;
[obj getValue:&match];
NSLog(@" Match found at index: %li", match.location);
}];
}
return 0;
}
嘆願のすべての場所を検索SE、私は[NSRegularExpressions] [1] になり –
...あなたの質問をより明確にする[1]:http://stackoverflow.com/questions/4353834/search-through-nsstring-using-正規表現 – EricS