John Ramos John Ramos - 1 year ago 105
iOS Question

Find index of Nth instance of substring in string in Swift

My Swift app involves searching through text in a UITextView. The user can search for a certain substring within that text view, then jump to any instance of that string in the text view (say, the third instance). I need to find out the integer value of which character they are on.

For example:

Example 1: The user searches for "hello" and the text view reads "hey hi hello, hey hi hello", then the user presses down arrow to view second instance. I need to know the integer value of the first

in the second hello (i.e. which # character that h in hello is within the text view). The integer value should be

Example 2: The user searches for "abc" while the text view reads "abcd" and they are looking for the first instance of
, so the integer value should be
(which is the integer value of that
since it's the first character of the instance they're searching for).

How can I get the index of the character the user is searching for?

Answer Source

Try like this:

let sentence = "hey hi hello, hey hi hello"
let query = "hello"
var searchRange = sentence.startIndex..<sentence.endIndex
var indexes: [String.Index] = []

while let range = sentence.rangeOfString(query, options: .CaseInsensitiveSearch, range: searchRange) {
    searchRange = range.endIndex..<searchRange.endIndex

print(indexes)   // "[7, 21]\n"

Xcode 8 beta 6 • Swift 3

while let range = sentence.range(of: query, options: .caseInsensitive, range: searchRange) {
    searchRange = range.upperBound..<searchRange.upperBound
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download