Skip to content

Instantly share code, notes, and snippets.

@mminer
Created March 1, 2017 00:52
Show Gist options
  • Save mminer/e62b5ee3d3ca04969d2016f22ff5500c to your computer and use it in GitHub Desktop.
Save mminer/e62b5ee3d3ca04969d2016f22ff5500c to your computer and use it in GitHub Desktop.
String extension to find the ranges of occurrences of a given string.
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