17

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.

4
  • 1
    Have a look at stackoverflow.com/questions/28182441/…, it shows various methods, including the .BackwardsSearch option. Commented Sep 30, 2016 at 11:41
  • You can use "some string".characters.indexOf('someChar') but it only works for chars.. Commented Sep 30, 2016 at 12:06
  • Please, check my answer @altralaser. Commented Apr 9, 2017 at 22:37
  • Please, check my answer @altralaser. Commented Dec 2, 2018 at 11:54

4 Answers 4

27
+50

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
Sign up to request clarification or add additional context in comments.

3 Comments

Why do you have offsetBy: -4 for the indexOf ?
@Laurent indexOf has an optional fromIndex: beginnersbook.com/2013/12/java-string-indexof-method-example
In Swift 5 the "lastIndexOf" code returns a String.Index, not an Int (like in Java). You could as well just do mystring.lastIndex(of: "."), which is shorter and also returns a String.Index. The problem is that there doesn't seem to be an easy way to convert that into a proper Int you can work with.
8
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

2 Comments

Printing the tests results in: 1. Optional(Swift.String.Index(_rawBits: 131072)), 2. Optional(Swift.String.Index(_rawBits: 589824)) - how did you get the actual int from it?
Problem is using this in substring.
8

If you want the returned value to be an 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)
    }
}

Comments

0

There is a built in swift function for finding the index of last occurrence of a character. The function signature is below

public func lastIndex(of element: Character) -> String.Index?{}

We can get the index for a character like below:

let url = "http://www.google.com/abc"
guard let lastIndexOfChar = url.lastIndex(of: "/") else { return nil }
let startIndex = url.index(lastIndexOfChar, offsetBy:1)
let substring = url[startIndex..<url.endIndex] // prints "abc"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.