如何使用location将Swift子字符串替换为Un Equal子字符串



不能使用模式的出现,因为文本可以在任何实例中更改。

var originalString = "Hi there <un>"
var stringToPut = "Some Amazing Name"
// Change string between 10th index and 13th to the following.
var requiredString = "Hi there <Some Amazing Name>"

这对于仅1个字符或替换字符串的长度相同时非常容易。但是,当父字符串的长度发生变化并且无法进行精确的位置引用时,子字符串的长度不相等时会中断。

希望这能奏效。

let originalString = "Hi there <un>"
let subString = "Some Amazing Name"
let characters = Array(originalString)
let firstPart = characters[0..<9]
let lastPart = characters[13..<characters.count]
let finaString = ("(String(firstPart))(subString)(String(lastPart))")

或者您可以使用replaceSubrange:

var originalString = "Hi there <un>"
var stringToPut = "Some Amazing Name"
// Change string between 10th index and 13th to the following.
var requiredString = "Hi there <Some Amazing Name>"
let startIndex = originalString.index(originalString.startIndex, offsetBy: 9)
let endIndex = originalString.index(originalString.startIndex, offsetBy: 12)
originalString.replaceSubrange(startIndex...endIndex, with: "Some Amazing Name") // "Hi there Some Amazing Name"

如果您知道<un>的格式,最简单的方法是:

let newString = originalString.replacingOccurrences(of: "<un>", with: stringToPut, options: .literal, range: nil)

最新更新