Reza Reza - 6 months ago 50
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{

Now I need to know the number of occurrence.


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")

This code prints 3.