Last active
August 19, 2019 14:05
-
-
Save kocyigityunus/eec1f7a0a2ed6767c1d8cc82dc631051 to your computer and use it in GitHub Desktop.
String + CharacterSet Examples
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
extension String { | |
func replacingOccurences(from characterSet: CharacterSet, with string: String) -> String { | |
return self.components(separatedBy: characterSet).joined(separator: string) | |
} | |
func isValid(for characterSet: CharacterSet) -> Bool { | |
let invalidCharacters = self.replacingOccurences(from: characterSet.inverted, with: "") | |
return invalidCharacters.isEmpty | |
} | |
} | |
" Test ".trimmingCharacters(in: CharacterSet.whitespaces) // "Test" | |
"123Test123".trimmingCharacters(in: CharacterSet.decimalDigits) // "Test" | |
" T e s t ".replacingOccurences(from: CharacterSet.whitespacesAndNewlines, with: "") // "Test" | |
" T e s t ".replacingOccurences(from: CharacterSet.whitespacesAndNewlines, with: "1") // "11T1e1s1t" | |
" Test ".isValid(for: .whitespacesAndNewlines) // false | |
"Test".isValid(for: .whitespaces) // true | |
"123".isValid(for: .decimalDigits) // false | |
"Yunus".isValid(for: .decimalDigits) // true | |
let emptyCharacterSet = CharacterSet(charactersIn: "") | |
"Yunus ".addingPercentEncoding(withAllowedCharacters: emptyCharacterSet) // "%59%75%6E%75%73%20" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment