Number of occurrences of substring in string in Swift

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

    Should you want to count characters rather than substrings:

    extension String {
        func count(of needle: Character) -> Int {
            return reduce(0) {
                $1 == needle ? $0 + 1 : $0
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-02 20:38

    Optimising dwsolbergs solution to count faster. Also faster than componentsSeparatedByString.

    extension String {
        /// stringToFind must be at least 1 character.
        func countInstances(of stringToFind: String) -> Int {
            assert(!stringToFind.isEmpty)
            var count = 0
            var searchRange: Range<String.Index>?
            while let foundRange = range(of: stringToFind, options: [], range: searchRange) {
                count += 1
                searchRange = Range(uncheckedBounds: (lower: foundRange.upperBound, upper: endIndex))
            }
            return count
        }
    }
    

    Usage:

    // return 2
    "aaaa".countInstances(of: "aa")
    
    • If you want to ignore accents, you may replace options: [] with options: .diacriticInsensitive like dwsolbergs did.
    • If you want to ignore case, you may replace options: [] with options: .caseInsensitive like ConfusionTowers suggested.
    • If you want to ignore both accents and case, you may replace options: [] with options: [.caseInsensitive, .diacriticInsensitive] like ConfusionTowers suggested.
    • If, on the other hand, you want the fastest comparison possible and you can guarantee some canonical form for composed character sequences, then you may consider option .literal and it will only perform exact matchs.
    0 讨论(0)
  • 2020-12-02 20:38

    why not just use some length maths??

    extension String {
        func occurences(of search:String) -> Int {
            guard search.count > 0 else {
                preconditionFailure()
            }
    
            let shrunk = self.replacingOccurrences(of: search, with: "")
    
            return (self.count - shrunk.count)/search.count
        }
    }
    
    0 讨论(0)
  • 2020-12-02 20:38

    Swift 5 Extension

    extension String {
    func numberOfOccurrencesOf(string: String) -> Int {
        return self.components(separatedBy:string).count - 1
    }
    

    }

    Example use

    let string = "hello Swift Swift and Swift"
    let numberOfOccurrences = string.numberOfOccurrencesOf(string: "Swift")
            
    // numberOfOccurrences = 3
    
    0 讨论(0)
  • 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")
    
    0 讨论(0)
提交回复
热议问题