xcode swift - 使用 replaceRange() 更改字符串中的某些出现

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37085076/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 08:47:48  来源:igfitidea点击:

swift - using replaceRange() to change certain occurrences in a string

iosxcodestringswift

提问by wasimsandhu

Say I have a string, and I want to change the first "a" in that string to an "e" in order to get the correct spelling.

假设我有一个字符串,我想将该字符串中的第一个“a”更改为“e”以获得正确的拼写。

let animal = "elaphant"

Using stringByReplacingOccurrencesOfString()will change every "a" in that string to an "e", returning:

使用stringByReplacingOccurrencesOfString()会将字符串中的每个“a”更改为“e”,返回:

elephent

I am trying to get the index of the first "a" and then replacing it using replaceRange(), like so:

我正在尝试获取第一个“a”的索引,然后使用 替换它replaceRange(),如下所示:

let index = animal.characters.indexOf("a")
let nextIndex = animal.startIndex.distanceTo(index!)
animal = animal.replaceRange(animal.startIndex.advancedBy(nextIndex)..<animal.startIndex.advancedBy(1), with: "e")

However, this code gives me the following error:

但是,此代码给了我以下错误:

Cannot assign value of type '()' to type 'String'

I have been trying to find a way to convert nextIndex into an Int, but I feel like I've got this whole method wrong. Help?

我一直试图找到一种方法将 nextIndex 转换为 an Int,但我觉得整个方法都错了。帮助?

回答by Blake Lockley

This is is what you want to do:

这就是你想要做的:

var animal = "elaphant"
if let range = animal.rangeOfString("a") {
  animal.replaceRange(range, with: "e")
}

rangeOfStringwill search for the first occurrence of the provided substring and if that substring can be found it will return a optional range otherwise it will return nil.

rangeOfString将搜索提供的子字符串的第一次出现,如果可以找到该子字符串,它将返回一个可选范围,否则将返回 nil。

we need to unwrap the optional and the safest way is with an if letstatement so we assign our range to the constant range.

我们需要解开可选项,最安全的方法是使用if let语句,因此我们将范围分配给常量range

The replaceRangewill do as it suggests, in this case we need animalto be a var.

replaceRange会做,因为它表明,在这种情况下,我们需要animal成为一个var

回答by Leo Dabus

update:

更新:

Swift 4.2 or later

Swift 4.2 或更高版本

var animal = "elaphant"
if let index = animal.firstIndex(of: "a") {
    animal.replaceSubrange(index...index, with: ["e"])
}


We can extend RangeReplaceableCollectionProtocol and create our own replaceFirstOccurrence(of: Element)method:

我们可以扩展RangeReplaceableCollection协议并创建我们自己的replaceFirstOccurrence(of: Element)方法:

extension RangeReplaceableCollection where Element: Equatable {
    mutating func replaceFirstOccurrence(of element: Element, with replacement: Element) {
        guard let index = firstIndex(of: element) else { return }
        replaceSubrange(index...index, with: CollectionOfOne(replacement))
    }
    func replacingFirstOccurrence(of element: Element, with replacement: Element) -> Self {
        var elements = self
        elements.replaceFirstOccurrence(of: element, with: replacement)
        return elements
    }
}


var animal = "elaphant"

// non mutating method
print(animal.replacingFirstOccurrence(of: "a", with: "e"))  // elephant
print(animal)     // still "elaphant"

// mutating method
animal.replaceFirstOccurrence(of: "a", with: "e")
print(animal)    // mutated to "elephant"

回答by Tanin

Swift4

斯威夫特4

var animal = "elaphant"

if let index = animal.index(of: "a") {
    animal.replaceSubrange(index...index, with: "e")
}

print (animal) // elephant

回答by iYoung

Tested in Playground:

在操场上测试:

var animal = "elaphant"
if let range = animal.rangeOfString("a") {
animal.replaceRange(range, with: "e")
}

print (animal)