stringByReplacingCharactersInRange does not work?

2019-08-28 07:13发布

问题:

I am attempting to replace a character with another one. For some reason stringByReplacingCharactersInRange does not work. I have not found a simple explanation on how to resolve this issue.

var binaryColor: String = "000"
(binaryColor as NSString).stringByReplacingCharactersInRange(NSMakeRange(0, 1), withString: "1")
println("This is binaryColor0: \(binaryColor)")

The result is 000 and not 100. Thanks for any help!

回答1:

You don't need to cast it to NSString to use stringByReplacingCharactersInRange you just need to change the way you create your string range as follow:

update: Xcode 7.2 • Swift 2.1.1

let binaryColor = "000"
let resultString = binaryColor.stringByReplacingCharactersInRange(
    Range(start: binaryColor.startIndex, end: binaryColor.startIndex.advancedBy(1)),
    withString: "1")

Or simply

let resultString2 = binaryColor.stringByReplacingCharactersInRange(
    binaryColor.startIndex..<binaryColor.startIndex.advancedBy(1),
    withString: "1")


回答2:

You have to set the variable:

var binaryColor: String = "000"
binaryColor = (binaryColor as NSString).stringByReplacingCharactersInRange(NSMakeRange(0, 1), withString: "1")
println("This is binaryColor0: \(binaryColor)")