Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift equivalent for Java indexOf and lastIndexOf of a string

Tags:

string

swift

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.

like image 593
altralaser Avatar asked Sep 30 '16 11:09

altralaser


2 Answers

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
like image 133
Danyl Avatar answered Sep 30 '22 08:09

Danyl


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
like image 33
Vladimir Kofman Avatar answered Sep 30 '22 08:09

Vladimir Kofman