I come from Java. I studied the Swift documentation and understood most of the concepts.
What I now looking for is an equivalent to the Java indexOf and lastIndexOf methods to finding positions of substring in a string.
I already found a solution with rangeOfString and using the startIndex property. That looks helpful for me to define the indexOf method.
But I think that rangeOfString only starts searching from the beginning of a string. Is this correct? And if so, how can I search in reverse direction (from end to start of the string)?
What I mean is to have f.e. the string "hello world" and if I start searching for "l" then I want to find the letter at position 9 and not at position 2.
In Swift 3
Java indexOf equivalent:
var index1 = string1.index(string1.endIndex, offsetBy: -4)
Java lastIndexOf equivalent:
var index2 = string2.range(of: ".", options: .backwards)?.lowerBound
extension String {
func indexOf(_ input: String,
options: String.CompareOptions = .literal) -> String.Index? {
return self.range(of: input, options: options)?.lowerBound
}
func lastIndexOf(_ input: String) -> String.Index? {
return indexOf(input, options: .backwards)
}
}
"hello world".indexOf("l") // 2
"hello world".lastIndexOf("l") // 9
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With