Skip to content

Instantly share code, notes, and snippets.

@bilawal-liaqat
Created October 19, 2018 12:43
Show Gist options
  • Save bilawal-liaqat/877fb89d82d72f4b644c35027f5c5157 to your computer and use it in GitHub Desktop.
Save bilawal-liaqat/877fb89d82d72f4b644c35027f5c5157 to your computer and use it in GitHub Desktop.
Swift string find substring index
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