My main string is \"hello Swift Swift and Swift\" and substring is Swift. I need to get the number of times the substring \"Swift\" occurs in the mentioned string.
T
Optimising dwsolbergs solution to count faster. Also faster than componentsSeparatedByString.
extension String {
/// stringToFind must be at least 1 character.
func countInstances(of stringToFind: String) -> Int {
assert(!stringToFind.isEmpty)
var count = 0
var searchRange: Range?
while let foundRange = range(of: stringToFind, options: [], range: searchRange) {
count += 1
searchRange = Range(uncheckedBounds: (lower: foundRange.upperBound, upper: endIndex))
}
return count
}
}
Usage:
// return 2
"aaaa".countInstances(of: "aa")
options: [] with options: .diacriticInsensitive like dwsolbergs did.options: [] with options: .caseInsensitive like ConfusionTowers suggested.options: [] with options: [.caseInsensitive, .diacriticInsensitive] like ConfusionTowers suggested.