remove a character from a string in swift

One way to remove a character from a string in Swift is to convert the string to a character array, remove the desired character from the array, and then create a new string from the modified array. Here's an example function that takes a string and a character to remove, and returns a new string with the character removed:

func removeCharFromString(_ str: String, _ charToRemove: Character) -> String {
    var chars = Array(str)  // convert string to character array
    if let index = chars.firstIndex(of: charToRemove) {
        chars.remove(at: index)  // remove desired character
    let modifiedStr = String(chars)  // create new string from modified array
    return modifiedStr
371 chars
9 lines

Here's an example usage of the function:

let str = "hello world"
let charToRemove: Character = "l"
let modifiedStr = removeCharFromString(str, charToRemove)
print(modifiedStr)  // prints 'heo world'
158 chars
5 lines

gistlibby LogSnag