John Ramos John Ramos - 2 months ago 29
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

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

Example 2: The user searches for "abc" while the text view reads "abcd" and they are looking for the first instance of
abc
, so the integer value should be
1
(which is the integer value of that
a
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

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
    indexes.append(range.startIndex)
}

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
    indexes.append(range.lowerBound)
}