在NSString中查找substring的所有位置(不只是第一个)

有一个string出现在一个string中多次。 我使用rangeOfString ,但似乎只能find第一个位置。 我怎样才能find子string的所有位置?

 NSString *subString1 = @"</content>"; NSString *subString2 = @"--\n"; NSRange range1 = [newresults rangeOfString:subString1]; NSRange range2 = [newresults rangeOfString:subString2]; int location1 = range1.location; int location2 = range2.location; NSLog(@"%i",location1); NSLog(@"%i",location2); 

您可以使用rangeOfString:options:range:并将第三个参数设置为超出第一个出现的范围。 例如,你可以做这样的事情:

 NSRange searchRange = NSMakeRange(0,string.length); NSRange foundRange; while (searchRange.location < string.length) { searchRange.length = string.length-searchRange.location; foundRange = [string rangeOfString:substring options:nil range:searchRange]; if (foundRange.location != NSNotFound) { // found an occurrence of the substring! do stuff here searchRange.location = foundRange.location+foundRange.length; } else { // no more substring to find break; } } 

将nil传递给[string rangeOfString:substring options:nil range:searchRange]; 显示警告。

为了摆脱这个警告,从这个组中枚举一个枚举

 enum { NSCaseInsensitiveSearch = 1, NSLiteralSearch = 2, NSBackwardsSearch = 4, NSAnchoredSearch = 8, NSNumericSearch = 64, NSDiacriticInsensitiveSearch = 128, NSWidthInsensitiveSearch = 256, NSForcedOrderingSearch = 512, NSRegularExpressionSearch = 1024 }; 

https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/index.html#//apple_ref/doc/constant_group/Search_and_Comparison_Options

这是我的解决scheme。 基本上,algorithm遍历string寻找子串匹配,并返回数组中的匹配。

由于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; } 

这里是PengOne的回答Swift 2.2中的一个版本,来自kevinlawler和Gibtang

注意:string和子string的types是NSString

 let fullStringLength = (string as String).characters.count var searchRange = NSMakeRange(0, fullStringLength) while searchRange.location < fullStringLength { searchRange.length = fullStringLength - searchRange.location let foundRange = string.rangeOfString(substring as String, options: .CaseInsensitiveSearch, range: searchRange) if foundRange.location != NSNotFound { // found an occurrence of the substring! do stuff here searchRange.location = foundRange.location + 1 } else { // no more strings to find break } } 

Swift 3.0

查找substring i所有位置

 let text = "This is the text and i want to replace something" let mutableAttributedString = NSMutableAttributedString(string: text) var searchRange = NSRange(location: 0, length: text.characters.count) var foundRange = NSRange() while searchRange.location < text.characters.count { searchRange.length = text.characters.count - searchRange.location foundRange = (text as NSString).range(of: "i", options: NSString.CompareOptions.caseInsensitive, range: searchRange) if foundRange.location != NSNotFound { // found an occurrence of the substring! do stuff here searchRange.location = foundRange.location + foundRange.length mutableAttributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: foundRange) } else { // no more substring to find break } } //Apply textLabel.attributedText = mutableAttributedString; 

而这个输出 –

在这里输入图像说明