यह मेरा समाधान है। असल में, एल्गोरिदम स्ट्रिंग को मैट्रिंग मैचों की तलाश में स्ट्रिंग करता है और उन मैचों को सरणी में देता है।
एनएसआरेंज एक संरचना है जिसे इसे सरणी में सीधे जोड़ा नहीं जा सकता है। NSValue का उपयोग करके, मैं एन्कोड पहले मैच को एन्कोड कर सकता हूं और फिर इसे सरणी में जोड़ सकता हूं। सीमा को पुनः प्राप्त करने के लिए, मैं डीकोडNSValue ऑब्जेक्ट एनएसआरेंज पर ऑब्जेक्ट।
#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;
}
याचिका का पता लगाएं से अधिक स्पष्ट अपने प्रश्न बना ... –
मैं [NSRegularExpressions] में [1] [1] दिखेगा: http://stackoverflow.com/questions/4353834/search-through-nsstring-using- नियमित अभिव्यक्ति – EricS