Number of occurrences of substring in string in Swift

后端 未结 11 964
夕颜
夕颜 2020-12-02 19:37

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.

T

11条回答
  •  暖寄归人
    2020-12-02 20:39

    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.components(separatedBy:"Swift")
    print(tok.count-1)
    

    This code prints 3.

    Edit: Before Swift 3 syntax the code looked like this:

    let tok =  s.componentsSeparatedByString("Swift")
    

提交回复
热议问题