Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
795 views
in Technique[技术] by (71.8m points)

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

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"

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

elephent

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'

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is is what you want to do:

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

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.

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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...