swift - 替换参数字符串中的字符

标签 swift string string-length inout

我想删除输入字符串。让我们从这个开始:

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 作为索引类型的部分原因是,用 IntString 下标会呈现错觉索引字符串是一个微不足道的操作 - 但情况并非总是如此,因为字符可以具有不同的字节长度,因此可能使索引成为 O(n) 操作。

尽管如果您的目标只是将 s 设置为包含所有零且计数与先前值相同的字符串,则您可以直接进行赋值:

func foo(s: inout String) {
    s = String(repeating: "0", count: s.characters.count)
}

关于swift - 替换参数字符串中的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42577551/

相关文章:

ios - 变量未在按钮按下操作内更新

swift - 确定 `true` 是 Bool 而不是等于 1 的数字

swift - 如何检查字符串是否包含 Swift 中的字母?

python - 子进程 "TypeError: a bytes-like object is required, not ' str'"

java - 为什么我的 java 猜谜游戏在第一个循环后不起作用

ios - 在 Swift 中使用协议(protocol)作为类型时出错

C++:如何实现自己的 String 类?

python - Python 中的字符串或列表替换

PHP - 获取数字中的数字长度