How to count the occurrences of a word in a string using Swift

3 Answers

0 votes
import Foundation

let str = "Swift compiled programming language. Swift general-purpose"
let word = "Swift"

let wordsArray = str.components(separatedBy: " ")
let count = wordsArray.filter { $0 == word }.count

print("The word '\(word)' occurs \(count) times")




/*
run:
     
The word 'Swift' occurs 2 times
     
*/
 

 



answered Mar 1, 2025 by avibootz
0 votes
import Foundation

let str = "Swift compiled programming language. Swift general-purpose"
let word = "Swift"
let pattern = "\\b\(word)\\b"

do {
    let regex = try NSRegularExpression(pattern: pattern, options: [])
    let matches = regex.matches(in: str, options: [], range: NSRange(location: 0, length: str.utf16.count))
    let count = matches.count
    print("The word '\(word)' occurs \(count) times")
} catch {
    print("Error creating regular expression: \(error)")
}



/*
run:
     
The word 'Swift' occurs 2 times
     
*/
 

 



answered Mar 1, 2025 by avibootz
0 votes
import Foundation

let str = "Swift compiled programming language. Swift general-purpose"
let word = "Swift"

let wordsArray = str.split(separator: " ")
let count = wordsArray.reduce(0) { $1 == word ? $0 + 1 : $0 }

print("The word '\(word)' occurs \(count) times")



/*
run:
     
The word 'Swift' occurs 2 times
     
*/
 

 



answered Mar 1, 2025 by avibootz
...