更改字符串中的某些匹配项

更改字符串中的某些匹配项

本文介绍了swift-使用replaceRange()更改字符串中的某些匹配项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个字符串,我想将该字符串中的第一个"a"更改为"e",以便获得正确的拼写.

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.

let animal = "elaphant"

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

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

elephent

我试图获取第一个"a"的索引,然后使用replaceRange()替换它,如下所示:

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

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'

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

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?

推荐答案

这是您要执行的操作:

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

rangeOfString将搜索提供的子字符串的第一个匹配项,如果可以找到该子字符串,它将返回一个可选范围,否则将返回nil.

rangeOfString will 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.

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

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

replaceRange将按照建议执行操作,在这种情况下,我们需要animal作为var.

The replaceRange will do as it suggests, in this case we need animal to be a var.

这篇关于swift-使用replaceRange()更改字符串中的某些匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 08:02