Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,181 questions

56,073 answers

573 users

How to find the starting index of all occurrences of a word in a string in Swift

1 Answer

0 votes
import Foundation

/*
    Find all starting indices of a word inside a larger text.
    This function uses String.range(of:) in a loop. Swift's string
    searching is Unicode‑aware and efficient, making this approach
    both expressive and reliable.
*/
func findAllOccurrences(in text: String, word: String) -> [Int] {
    // Searching for an empty word is meaningless
    guard !word.isEmpty else { return [] }

    var indices: [Int] = []
    var searchStart = text.startIndex

    /*
        Loop:
        - Search for the next occurrence starting at `searchStart`.
        - Convert the found range's lowerBound into an integer offset.
        - Move forward by one character to allow overlapping matches.
    */
    while let range = text.range(of: word, range: searchStart..<text.endIndex) {
        let index = text.distance(from: text.startIndex, to: range.lowerBound)
        indices.append(index)

        // Move forward by one character
        searchStart = text.index(range.lowerBound, offsetBy: 1)
    }

    return indices
}

let text =
    "the quick brown fox jumps over the lazy dog. the fox is clever."
let word = "the"

print("Text: \(text)")
print("Word: \"\(word)\"\n")
print("Occurrences at indices:")

for idx in findAllOccurrences(in: text, word: word) {
    print(idx)
}


/*
run:

Text: the quick brown fox jumps over the lazy dog. the fox is clever.
Word: "the"

Occurrences at indices:
0
31
45

*/

 



answered Aug 30 by avibootz

Related questions

...