更好的方法来替换Swift中的指标之间的子串?

时间:2017-06-16 16:27:32

标签: ios swift string

我有一个"this is my title {{and this is what I have to replace}}"形式的字符串。

到目前为止,我发现的最佳方式是:

    let from = originalTitle.firstIndex(of: "{{") ?? 0
    let to = originalTitle.firstIndex(of: "}}") ?? 0

    if let textToReplace = originalTitle.slicing(from: from, to: to), !textToReplace.isEmpty {
        return originalTitle.replacing(textToReplace, with: "XY")
    }

    return originalTitle

但是我觉得必须有一种更好的方法来明确指出两个占位符或标记然后替换里面的内容。有什么想法吗?

提前致谢!

1 个答案:

答案 0 :(得分:0)

到目前为止更好的可能性:

    if let from = originalTitle.range(of: "{{")?.lowerBound, let to = originalTitle.range(of: "}}")?.upperBound {
        let range = from..<to
        return originalTitle.replacingCharacters(in: range, with: "XY")
    }
    return originalTitle