Swift equivalent for Java indexOf and lastIndexOf strings

I come from Java. I studied the Swift documentation and understood most of the concepts.

What I'm looking for right now is equivalent to the Java indexOf and lastIndexOf methods for finding the substring positions in a string.

I already found a solution with rangeOfString and used the startIndex property. It seems to me useful to define the indexOf method.

But I think that rangeOfString is just starting the search from the beginning of the line. It's right? And if so, how can I search in the opposite direction (from end to beginning of line)?

What I mean is the fe string "hello world", and if I start looking for "l", then I want to find the letter at position 9, not at position 2.

+5
source share
3 answers

In Swift 3

Java equivalent of indexOf:

var index1 = string1.index(string1.endIndex, offsetBy: -4) 

Java lastIndexOf:

  var index2 = string2.range(of: ".", options: .backwards)?.lowerBound 
+15
source
 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 
+4
source

If you want the return value to be Int:

 extension String { func lastIndex(of string: String) -> Int? { guard let index = range(of: string, options: .backwards) else { return nil } return self.distance(from: self.startIndex, to: index.lowerBound) } } 
+2
source

Source: https://habr.com/ru/post/1257517/


All Articles