replace a character in a string in swift

To replace a specific character in a string in Swift, you can use the replacingOccurrences method. Here is an example code block:

main.swift
var myString = "hello"
let index = myString.index(myString.startIndex, offsetBy: 1)
myString = myString.replacingOccurrences(of: "e", with: "a", options: .literal, range: index..<myString.endIndex)
print(myString) // Output: hallo
231 chars
5 lines

In this example, we replace the second character e in the string myString with an a. index is used to specify the range where the replacingOccurrences method will look for the character to replace. The options parameter is set to .literal, which matches the characters exactly, and the range parameter defines the range of the string where the replacement should occur.

related categories

gistlibby LogSnag