Created
March 1, 2017 00:52
-
-
Save mminer/e62b5ee3d3ca04969d2016f22ff5500c to your computer and use it in GitHub Desktop.
String extension to find the ranges of occurrences of a given string.
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
import Foundation | |
extension String { | |
/// Finds and returns the ranges of occurrences of a given string within a given range of the `String`. | |
func ranges(of searchString: String, options: CompareOptions = [], range searchRange: Range<Index>? = nil, locale: Locale? = nil) -> [Range<Index>] { | |
let searchRange = searchRange ?? startIndex..<endIndex | |
if let foundRange = range(of: searchString, options: options, range: searchRange, locale: locale) { | |
let nextRange = foundRange.upperBound..<searchRange.upperBound | |
return [foundRange] + ranges(of: searchString, options: options, range: nextRange, locale: locale) | |
} else { | |
return [] | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment