Skip to content

Instantly share code, notes, and snippets.

@dnsmob
Created April 2, 2019 07:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dnsmob/2001ba6f28c479acfc13025e27da91b8 to your computer and use it in GitHub Desktop.
Save dnsmob/2001ba6f28c479acfc13025e27da91b8 to your computer and use it in GitHub Desktop.
// https://stackoverflow.com/questions/32305891/index-of-a-substring-in-a-string-with-swift
extension StringProtocol where Index == String.Index {
func index(of string: Self, options: String.CompareOptions = []) -> Index? {
return range(of: string, options: options)?.lowerBound
}
func endIndex(of string: Self, options: String.CompareOptions = []) -> Index? {
return range(of: string, options: options)?.upperBound
}
func indexes(of string: Self, options: String.CompareOptions = []) -> [Index] {
var result: [Index] = []
var start = startIndex
while start < endIndex,
let range = self[start..<endIndex].range(of: string, options: options) {
result.append(range.lowerBound)
start = range.lowerBound < range.upperBound ? range.upperBound :
index(range.lowerBound, offsetBy: 1, limitedBy: endIndex) ?? endIndex
}
return result
}
func ranges(of string: Self, options: String.CompareOptions = []) -> [Range<Index>] {
var result: [Range<Index>] = []
var start = startIndex
while start < endIndex,
let range = self[start..<endIndex].range(of: string, options: options) {
result.append(range)
start = range.lowerBound < range.upperBound ? range.upperBound :
index(range.lowerBound, offsetBy: 1, limitedBy: endIndex) ?? endIndex
}
return result
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment