Created
May 1, 2016 00:19
-
-
Save joshavant/d9a94373ec45a7b5d7e7d98263e46e1e to your computer and use it in GitHub Desktop.
Replace characters from set with replacement 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 { | |
func replaceCharactersFromSet(characterSet: NSCharacterSet, replacementString: String) -> String { | |
let scanner = NSScanner(string: self) | |
scanner.charactersToBeSkipped = nil | |
let sanitizedString = NSMutableString(capacity: self.characters.count) | |
while(!scanner.atEnd) { | |
var buffer: NSString? = "" | |
if scanner.scanUpToCharactersFromSet(characterSet, intoString: &buffer), let buffer = buffer { | |
sanitizedString.appendString(buffer as String) | |
} else { | |
scanner.scanLocation = scanner.scanLocation + 1 | |
sanitizedString.appendString(replacementString as String) | |
} | |
} | |
return sanitizedString as String | |
} | |
} |
KevinLaRosa
commented
Oct 9, 2018
@AliSoftware answer but in Swift 4/5
extension String {
func replaceCharactersFromSet(characterSet: CharacterSet, replacementString: String = "") -> String {
return components(separatedBy: characterSet).joined(separator: replacementString)
}
}
👍
Useful, thanks.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment