Index of substring in string?

Does the standard library has something like this?:

let someString = "This is a wonderful day"

// returns 10 because that's where wonderful starts at
let index = someString.firstIndex(of: "wonderful")! 
1 Like

You can use the range(of:) method that becomes available on String (bridged from from NSString) when you import Foundation

import Foundation

let someString = "This is a wonderful day"

// returns 10 because that's where wonderful starts at
let index = someString.range(of: "wonderful")!.lowerBound

print(someString[index]) // => "w"
2 Likes

See this very useful explainer:

I'll point out specifically this excerpt:

I'll echo what @jrose said above — very often, the use cases I've seen for random access into String s have been pretty much contrived. It's extremely rare to need to actually jump around inside of a String and very often, by the time you're doing that, you're either not really benefitting from the semantic correctness that String offers, or you really need a different data structure.

If you’re into learning and implementing algorithms yourself, I highly recommend reading about substring search algorithms.

There’s a clever method to get from the naive O(mn) to O(n) at the cost of O(m) space, and then a much more complicated way to do it in O(1) space.

Several of the classic algorithms assume a finite alphabet, which is not the case for strings in Swift. Attempting to adapt them may or may not be possible.

Here’s a page with primers on a large number of string-search algorithms: ESMAJ

1 Like