Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 777
owlswipe Avatar asked Sep 06 '16 22:09

owlswipe


People also ask

Can you index a string in Swift?

To access certain parts of a string or to modify it, Swift provides the Swift. Index type which represents the position of each Character in a String. The above prefix(upTo:) method returns a Substring and not a String.

How do I find substrings in Swift?

To find substring of a String in Swift, prepare Range object using start and end indices, then give this Range object to the string in square brackets as an index.

How do I get a single character from a string in Swift?

The swift string class does not provide the ability to get a character at a specific index because of its native support for UTF characters. The variable length of a UTF character in memory makes jumping directly to a character impossible. That means you have to manually loop over the string each time.


1 Answers

Xcode 11 • Swift 5 or later

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

while let range = sentence.range(of: query, options: .caseInsensitive, range: searchRange) {
    searchRange = range.upperBound..<searchRange.upperBound
    indices.append(range.lowerBound)
}

print(indices)   // "[7, 21]\n"
like image 196
Leo Dabus Avatar answered Nov 10 '22 17:11

Leo Dabus