In Swift, you can find the range of a substring using range(of:), which comes from Foundation, so a standalone file needs import Foundation at the top:
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:
import Foundation
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.
Free plan: 30 tutor messages. PRO is unlimited.
