Number of occurrences of substring in string in Swift

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

    I'd recommend an extension to string in Swift 3 such as:

    extension String {
        func countInstances(of stringToFind: String) -> Int {
            var stringToSearch = self
            var count = 0
            while let foundRange = stringToSearch.range(of: stringToFind, options: .diacriticInsensitive) {
                stringToSearch = stringToSearch.replacingCharacters(in: foundRange, with: "")
                count += 1
            }
            return count
        }
    }
    

    It's a loop that finds and removes each instance of the stringToFind, incrementing the count on each go-round. Once the searchString no longer contains any stringToFind, the loop breaks and the count returns.

    Note that I'm using .diacriticInsensitive so it ignore accents (for example résume and resume would both be found). You might want to add or change the options depending on the types of strings you want to find.

提交回复
热议问题