distance(from:to:) String method calculates the difference between two String.Index values:
let mystring = "hi this is my name" if let range = mystring.range(of: "this") { let startPos = mystring.distance(from: mystring.startIndex, to: range.lowerBound) let endPos = mystring.distance(from: mystring.startIndex, to: range.upperBound) print(startPos, endPos) // 3 7 }
In fact, it just redirects the call to the CharacterView string, so the above gives the same result as
let mystring = "hi this is my name" if let range = mystring.range(of: "this") { let startPos = mystring.characters.distance(from: mystring.characters.startIndex, to: range.lowerBound) let endPos = mystring.characters.distance(from: mystring.characters.startIndex, to: range.upperBound) print(startPos, endPos) // 3 7 }
If you need all occurrences of a string:
let mystring = "this is this and that is that" var searchPosition = mystring.startIndex while let range = mystring.range(of: "this", range: searchPosition..<mystring.endIndex) { let startPos = mystring.distance(from: mystring.startIndex, to: range.lowerBound) let endPos = mystring.distance(from: mystring.startIndex, to: range.upperBound) print(startPos, endPos) searchPosition = range.upperBound }
Martin r
source share