Number of occurrences of substring in string in Swift

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

    My solution, maybe it will be better to use String.Index instead of Int range but I think in such way it is a bit easier to read.

    extension String {
        func count(of char: Character, range: (Int, Int)? = nil) -> Int {
            let range = range ?? (0, self.count)
    
            return self.enumerated().reduce(0) {
                guard ($1.0 >= range.0) && ($1.0 < range.1) else { return $0 }
                return ($1.1 == char) ? $0 + 1 : $0
            }
        }
    }
    

提交回复
热议问题