替换参数字符串中的字符

Replacing characters in a parameter string

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

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 也不行。

如何替换参数字符串中的字符?

您需要为此目的使用可变字符串。这是Swift3.0

中编写的完整代码
var string: NSMutableString = "This is my string."

    func foo(s: NSMutableString)
    {
        s.replaceCharacters(in: NSRange(location:0, length: s.length - 1 ), with: String(repeating: "0", count: s.length))
        print(s)
    }

    foo(s: string) //Function Calling

输出: 000000000000000000

一个StringCharacterView isn't indexed by Int, rather it is indexed by the opaque 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:) and index(_:offsetBy:) on String in order to offset the indices for the lower and upper bound of the range (these methods also just forward onto the string's character view). A good summary of these methods is given in

不使用 Int 作为索引类型的部分原因是,用 Int 下标 String 会让人产生这样的错觉,即索引字符串是一个琐碎的操作——情况并非总是如此,因为字符可以有不同的字节长度,因此可能使索引成为一个 O(n) 操作。

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

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