Reza Reza - 1 year ago 110
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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download