我想删除输入字符串。让我们从这个开始:
func foo(s: String) {
s.replaceSubrange(0..<s.characters.count,
with: String(repeating: "0", count: s.characters.count))
}
不出所料,这会导致
cannot use mutating member on immutable value: 's' is a 'let' constant
很好:
func foo(s: inout String) {
s.replaceSubrange(0..<s.characters.count,
with: String(repeating: "0", count: s.characters.count))
}
但现在:
'inout String' is not convertible to 'String'
指向.character
——什么?!
奇怪的是,当我这样做时:
func foo(s: inout String) {
let n = s.characters.count
s.replaceSubrange(0..<n,
with: String(repeating: "0", count: n))
}
对.characters
的调用完全没问题,但是
cannot invoke 'replaceSubrange' with an argument list of type '(CountableRange, with: String)'
使用 0...n-1
也不起作用。
如何替换参数字符串中的字符?
最佳答案
字符串
的 CharacterView
不是由 Int
索引的,而是由不透明的 String.Index
索引的类型。因此你想说:
func foo(s: inout String) {
s.replaceSubrange(s.startIndex..<s.endIndex,
with: String(repeating: "0", count: s.characters.count))
}
我们没有直接使用字符串的characters
属性来获取开始或结束索引,正如String
在其API中提供的那样为了方便起见 - 但它们只是转发到 CharacterView
上。
要替换不同的子范围,您可能需要使用各种索引方法,例如 index(after:)
, index(before:)
和 index(_:offsetBy:)
在 String
上,以便偏移范围下限和上限的索引(这些方法也只是转发到字符串的字符 View )。 this Q&A 中给出了这些方法的一个很好的总结。 .
不使用 Int
作为索引类型的部分原因是,用 Int
为 String
下标会呈现错觉索引字符串是一个微不足道的操作 - 但情况并非总是如此,因为字符可以具有不同的字节长度,因此可能使索引成为 O(n) 操作。
尽管如果您的目标只是将 s
设置为包含所有零且计数与先前值相同的字符串,则您可以直接进行赋值:
func foo(s: inout String) {
s = String(repeating: "0", count: s.characters.count)
}
关于swift - 替换参数字符串中的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42577551/