Swift find all occurrences of a substring

前端 未结 7 1928
无人及你
无人及你 2020-12-06 00:46

I have an extension here of the String class in Swift that returns the index of the first letter of a given substring.

Can anybody please help me make it so it will

相关标签:
7条回答
  • 2020-12-06 01:16

    Please check the following answer for finding multiple items in multiple locations

    func indicesOf(string: String) -> [Int] {
        var indices = [Int]()
        var searchStartIndex = self.startIndex
        
        while searchStartIndex < self.endIndex,
            let range = self.range(of: string, range: searchStartIndex..<self.endIndex),
            !range.isEmpty
        {
            let index = distance(from: self.startIndex, to: range.lowerBound)
            indices.append(index)
            searchStartIndex = range.upperBound
        }
        
        return indices
    }
    
    func attributedStringWithColor(_ strings: [String], color: UIColor, characterSpacing: UInt? = nil) -> NSAttributedString {
        let attributedString = NSMutableAttributedString(string: self)
        for string in strings {
            let indexes = self.indicesOf(string: string)
            for index in indexes {
                let range = NSRange(location: index, length: string.count)
                attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range)
            }
        }
        
        guard let characterSpacing = characterSpacing else {return attributedString}
        
        attributedString.addAttribute(NSAttributedString.Key.kern, value: characterSpacing, range: NSRange(location: 0, length: attributedString.length))
        
        return attributedString
    }
    

    can be used as follows :

    let message = "Item 1 + Item 2 + Item 3"
    message.attributedStringWithColor(["Item", "+"], color: UIColor.red)
    

    and gets the result

    0 讨论(0)
提交回复
热议问题