Number of occurrences of substring in string in Swift

后端 未结 11 986
夕颜
夕颜 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:33

    For the sake of completeness – and because there is a regex tag – this is a solution with Regular Expression

    let string = "hello Swift Swift and Swift"
    let regex = try! NSRegularExpression(pattern: "swift", options: .caseInsensitive)
    let numberOfOccurrences = regex.numberOfMatches(in: string, range: NSRange(string.startIndex..., in: string))
    

    The option .caseInsensitive is optional.

提交回复
热议问题