Reza Reza - 12 days ago 6
Swift Question

Swift :: Number of occurrences of substring in string

My main string is "hello Swift Swift and Swift" and substring is Swift.
I need to get the number of times the substring "Swift" occurs in the mentioned string.

This code can determine whether the patter exists.
var string = "hello Swift Swift and Swift"

if string.rangeOfString("Swift") != nil{
println("exists")
}


Now I need to know the number of occurrence.

Answer

A simple approach would be to split on "Swift", and subtract 1 from the number of parts:

let s = "hello Swift Swift and Swift"
let tok =  s.componentsSeparatedByString("Swift")
println(tok.count-1)

This code prints 3.

Comments