Number of occurrences of substring in string in Swift

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

    I needed a way to count substrings that may contain the start of the next matched substring. Leveraging dwsolbergs extension and Strings range(of:options:range:locale:) method I came up with this String extension

    extension String
    {
        /**
         Counts the occurrences of a given substring by calling Strings `range(of:options:range:locale:)` method multiple times.
    
         - Parameter substring : The string to search for, optional for convenience
    
         - Parameter allowOverlap : Bool flag indicating whether the matched substrings may overlap. Count of "

提交回复
热议问题