计算 swift 中从单词到字符串末尾的字符串范围

Calculate range of string from word to end of string in swift

我有一个 NSMutatableString:

var string: String = "Due in %@ (%@) $%@.\nOverdue! Please pay now %@"
attributedText = NSMutableAttributedString(string: string, attributes: attributes)

如何计算swift中单词Overdue的长度和起始索引?

到目前为止我已经尝试过:

let startIndex = attributedText.string.rangeOfString("Overdue")
let range = startIndex..<attributedText.string.finishIndex

// Access the substring.
let substring = value[range]
print(substring)

但是没用。

您应该先生成结果字符串:

let string = String(format: "Due in %@ (%@) $%@.\nOverdue! Please pay now %@", "some date", "something", "15", "some date")

然后用.disTanceTo得到索引之间的距离;

if let range = string.rangeOfString("Overdue") {
  let start = string.startIndex.distanceTo(range.startIndex)
  let length = range.startIndex.distanceTo(string.endIndex)

  let wordToEndRange = NSRange(location: start, length: length) 
  // This is the range you need

  attributedText.addAttribute(NSForegroundColorAttributeName, 
     value: UIColor.blueColor(), range: wordToEndRange)
}


请注意,如果字符串包含表情符号或其他 Unicode 字符,NSRange 将无法正常工作,因此上述解决方案可能无法在这种情况下正常工作。

请查看以下 SO 答案以获得更好的解决方案,该解决方案也涵盖了这种情况:

看看这个,

                let nsString = element.text as NSString
                let range = nsString.range(of: word, options: .widthInsensitive)
                let att: [NSAttributedString.Key: Any] = [.foregroundColor: UIColor.systemBlue]
                attText.addAttributes(att, range: NSRange(location: range.location, length: range.length))