Swift Tutorial
Swift Data Types
Swift Control Flow
Swift Functions
Swift Collections
Swift OOPs
Swift Additional Topics
If you want to remove a specific character from a string in Swift, one of the most straightforward approaches is to use the replacingOccurrences(of:with:)
method from the String
type.
Here's how you can do it:
var str = "Hello, World!" str = str.replacingOccurrences(of: "!", with: "") print(str) // "Hello, World"
In this example, we're removing the "!" character from the string "Hello, World!".
However, this method will replace all occurrences of the specified character. If you only want to remove the first occurrence or have other specific requirements, you'd need to take a different approach.
Swift remove specific character from string:
replacingOccurrences(of:with:)
method.var word = "Hello" let characterToRemove: Character = "l" word = word.replacingOccurrences(of: String(characterToRemove), with: "") print(word) // Output: Heo
Remove character at index in Swift string:
var text = "Swift" let indexToRemove = text.index(text.startIndex, offsetBy: 2) text.remove(at: indexToRemove) print(text) // Output: Sift
How to delete a character from Swift string:
replacingOccurrences(of:with:)
or creating a new string without the character.var message = "Goodbye" let characterToRemove: Character = "o" message = message.replacingOccurrences(of: String(characterToRemove), with: "") print(message) // Output: Gdbye
Swift string remove method for specific character:
replacingOccurrences(of:with:)
method to remove specific characters from a string.var phrase = "Swift is awesome" let characterToRemove: Character = " " phrase = phrase.replacingOccurrences(of: String(characterToRemove), with: "") print(phrase) // Output: Swiftisawesome
Remove specific character from Swift string at position:
replacingOccurrences(of:with:)
method.var word = "Fantastic" let position = 3 word.remove(at: word.index(word.startIndex, offsetBy: position)) print(word) // Output: Fanastic
Swift remove character by value from string:
replacingOccurrences(of:with:)
method.var text = "Mississippi" let characterToRemove: Character = "i" text = text.replacingOccurrences(of: String(characterToRemove), with: "") print(text) // Output: Msssspp
Deleting characters in Swift string at a specific index:
remove(at:)
method.var word = "Hello" let indexToRemove = word.index(word.startIndex, offsetBy: 1) word.remove(at: indexToRemove) print(word) // Output: Helo
Remove a character from Swift string example:
replacingOccurrences(of:with:)
method or by creating a new string without the character.var text = "Programming" let characterToRemove: Character = "m" text = text.replacingOccurrences(of: String(characterToRemove), with: "") print(text) // Output: Prograing
Swift string manipulation: remove character at index:
remove(at:)
method.var name = "Jonathan" let indexToRemove = name.index(name.startIndex, offsetBy: 4) name.remove(at: indexToRemove) print(name) // Output: Jonaathan