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