Find all locations of substring in NSString (not just first)

后端 未结 6 1838
广开言路
广开言路 2020-11-30 04:12

There is a substring that occurs in a string several times. I use rangeOfString, but it seems that it can only find the first location. How can I find all the l

6条回答
  •  我在风中等你
    2020-11-30 04:43

    Swift 3.0

    Find all locations of substring i

    let text = "This is the text and i want to replace something"
    let mutableAttributedString = NSMutableAttributedString(string: text)
    
    var searchRange = NSRange(location: 0, length: text.characters.count)
    var foundRange = NSRange()
    while searchRange.location < text.characters.count {
        searchRange.length = text.characters.count - searchRange.location
        foundRange = (text as NSString).range(of: "i", options: NSString.CompareOptions.caseInsensitive, range: searchRange)
        if foundRange.location != NSNotFound {
            // found an occurrence of the substring! do stuff here
            searchRange.location = foundRange.location + foundRange.length
            mutableAttributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: foundRange)
        }
        else {
            // no more substring to find
            break
        }
    }
    
    //Apply
    textLabel.attributedText = mutableAttributedString;
    

    And this output-

提交回复
热议问题