Created
April 2, 2019 07:55
-
-
Save dnsmob/2001ba6f28c479acfc13025e27da91b8 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// 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