我试图用另一个子字符串替换子字符串但我收到此错误:
cannot convert value of type 'String.Index' (aka 'String.CharacterView.Index') to expected argument type 'Range<String.Index>' (aka 'Range<String.CharacterView.Index>')
这是我的代码:
// This are the position of the substrings:
let rangeOne = strToSort.index(strToSort.startIndex, offsetBy: (i-1))
let rangeTwo = strToSort.index(strToSort.startIndex, offsetBy: (i))
Here is where I try to make the replacement:
strToSort = strToSort.replacingCharacters(in: rangeOne, with: strToSort.substring(with: rangeTwo))
但是我收到了这个错误:
你们中的任何人都知道我做错了什么或者解决了这个问题吗?
我真的很感谢你的帮助
答案 0 :(得分:1)
像这样修改你的代码
var strToSort = "HELLOAGAIN"
let rangeOne = strToSort.index(strToSort.startIndex, offsetBy: (2))
let rangeTwo = strToSort.index(strToSort.startIndex, offsetBy: (3))
let stringRange = Range(uncheckedBounds: (lower: rangeOne, upper: rangeTwo))
strToSort = strToSort.replacingCharacters(in: stringRange, with: strToSort)
print(strToSort)
在代码中没有定义范围和方法
的 replacingCharacters 强>
需要类型的参数
Range<String.Index>
并且您提供的类型String.Index
不正确,因此您收到错误。
如果你想用E代替字符串H的出现,可以使用不同的String
方法,如
let aString: String = "HELLO"
let newString = aString.stringByReplacingOccurrencesOfString("H", withString: "E", options: NSStringCompareOptions.LiteralSearch, range: nil)