我希望将从一个字符的索引开始的字符串替换为另一个字符的结尾。示例将字符串(
中的)
索引中的所有字符替换为Somesong here - Artist (radio edit)
的索引,或者即使字符串为Somesong here - Artist (radio edit) (another one)
。任何帮助将不胜感激。
我已经尝试了这个,但我不认为我会解决,我不太确定如何从一个范围开始删除子串。
var a = "Somesong here - Artist (radio edit)"
let range = a.rangeOfString("(")
let range2 = a.rangeOfString(")")
答案 0 :(得分:0)
你可以像这样使用-
范围:
var str = "Somesong here - Artist (radio edit)"
if let range = str.rangeOfString("-") {
// str = Somesong here
str.removeRange(range.startIndex..<str.endIndex)
}
// str = Somesong here - New Artist
str += "- New Artist"
如果您想使用(
范围:
var str = "Somesong here - Artist (radio edit)"
if let range = str.rangeOfString("(") {
// str = Somesong here - Artist
str.removeRange(range.startIndex..<str.endIndex)
}
// str = Somesong here - Artist (not a radio edit)
str += "(not a radio edit)"
您可以使用str += ...
添加if let
。
答案 1 :(得分:0)
使用两个范围创建新范围并致电replaceRange
:
var a = "Somesong here - Artist (radio edit)"
let range = a.rangeOfString("(")
let range2 = a.rangeOfString(")")
a.replaceRange(range!.startIndex...range2!.startIndex, with: "(live version)")
print(a) // Somesong here - Artist (live version)