Last active
August 9, 2019 08:18
-
-
Save dagronf/18bd95d8b7f8b6f2e519681f7599c87e to your computer and use it in GitHub Desktop.
Simple remove/replace characters in a swift string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
extension String { | |
/// Returns a new string by removing any instances of the specified characters | |
/// | |
/// - Parameter | |
/// - replacementChars: String containing the characters to replace | |
/// - Returns: a new string filtering out the specified characters | |
func removing(charactersIn replacementChars: String) -> String { | |
return self.filter { replacementChars.contains($0) == false } | |
} | |
/// Removes any instances of the specified characters | |
/// | |
/// - Parameter | |
/// - replacementChars: String containing the characters to replace | |
/// - Returns: a new string filtering out the specified characters | |
mutating func remove(charactersIn replacementChars: String) { | |
self = self.removing(charactersIn: replacementChars) | |
} | |
/// Returns a new string by replacing any instances of the specified characters with a new character | |
/// | |
/// - Parameters: | |
/// - charactersIn: String containing the characters to replace | |
/// - replacement: replacement character | |
func replacing(charactersIn replacementChars: String, with replacement: Character) -> String { | |
return String(self.map { replacementChars.contains($0) ? replacement : $0 }) | |
} | |
/// Replaces any instances of the specified characters with a new character | |
/// | |
/// - Parameters: | |
/// - charactersIn: String containing the characters to replace | |
/// - replacement: replacement character | |
mutating func replace(charactersIn replacementChars: String, with replacement: Character) { | |
self = self.replacing(charactersIn: replacementChars, with: replacement) | |
} | |
} |
Author
dagronf
commented
Jan 30, 2019
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment