Start learning free

LESSON 61 OF 349 · STRINGS I

String Find in Swift in Swift

Lesson

In Swift, you can find the range of a substring using range(of:):

s.range(of: sub)                                    // returns Range? of first occurrence, or nil if not found
s.range(of: sub, options: .backwards)              // returns Range? of last occurrence
s.range(of: sub, range: fromIdx..

Here are some examples:

let sentence = "Hello World"
if let range = sentence.range(of: "World") {
    let idx = sentence.distance(from: sentence.startIndex, to: range.lowerBound)
    print(idx)  // 6
}

print(sentence.range(of: "xyz"))  // nil  (not found)

The index returned is the position of the first character of the found substring.


Assignment
Follow the Coding Tutorial and find the index of "World" in sentence!


Hint
Use sentence.range(of: "World") to locate the substring (it returns an optional; ! unwraps it when you know the substring is there), then store the distance from sentence.startIndex to its lowerBound in index.

STEP 1 OF 1
    Ctrl + Enter to check

    String Find in Swift

    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free