How to replace nth character of a string with another

I've found this solution.

var string = "Cars"
let index = string.index(string.startIndex, offsetBy: 2)
string.replaceSubrange(index...index, with: "t")
print(string)
// Cats

Solutions that use NSString methods will fail for any strings with multi-byte Unicode characters. Here are two Swift-native ways to approach the problem:

You can use the fact that a String is a sequence of Character to convert the string to an array, modify it, and convert the array back:

func replace(myString: String, _ index: Int, _ newChar: Character) -> String {
    var chars = Array(myString)     // gets an array of characters
    chars[index] = newChar
    let modifiedString = String(chars)
    return modifiedString
}

replace("House", 2, "r")
// Horse

Alternately, you can step through the string yourself:

func replace(myString: String, _ index: Int, _ newChar: Character) -> String {
    var modifiedString = String()
    for (i, char) in myString.characters.enumerate() {
        modifiedString += String((i == index) ? newChar : char)
    }
    return modifiedString
}

Since these stay entirely within Swift, they're both Unicode-safe:

replace("🏠🏡🏠🏡🏠", 2, "🐴")
// 🏠🏡🐴🏡🏠

In Swift 4 it's much easier.

let newString = oldString.prefix(n) + char + oldString.dropFirst(n + 1)

This is an example:

let oldString = "Hello, playground"
let newString = oldString.prefix(4) + "0" + oldString.dropFirst(5)

where the result is

Hell0, playground

The type of newString is Substring. Both prefix and dropFirst return Substring. Substring is a slice of a string, in other words, substrings are fast because you don't need to allocate memory for the content of the string, but the same storage space as the original string is used.

Tags:

String

Swift