Ios 替换Swift中指示器之间的子字符串的更好方法?
我有一个字符串,格式为Ios 替换Swift中指示器之间的子字符串的更好方法?,ios,swift,string,Ios,Swift,String,我有一个字符串,格式为“这是我的标题{{这是我必须替换的}” 到目前为止,我发现最好的方法是: let from = originalTitle.firstIndex(of: "{{") ?? 0 let to = originalTitle.firstIndex(of: "}}") ?? 0 if let textToReplace = originalTitle.slicing(from: from, to: to), !textToReplace.isEmpty
“这是我的标题{{这是我必须替换的}”
到目前为止,我发现最好的方法是:
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
然而,我觉得必须有一种更好的方法来显式地指示两个占位符或标记,然后替换其中的内容。有什么想法吗
提前谢谢 到目前为止,更好的可能性是:
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
如果let-from=originalTitle.range(of:“{”)?.lowerBound,则let-to=originalTitle.range(of:“}”)?.upperBound{
让range=from...firstIndex(of:)
和slicing(from:to:)
方法从何而来?可能的重复:,。您查看过这些方法吗?是否要替换所有出现的{…}
还是只有一个?分隔符是固定的还是可变的?@JAL这里提供了最好的解决方案,还有我检查过的一些类似的解决方案,其中有regexs。我试图避开这些,因为这是一个需要解释的练习students@MartinR可能有N次出现,并且分隔符总是那些“}}”恰好出现在“{{在字符串中?@MartinR我们可以安全地忽略它,因为它不符合占位符IIRC