Skip to content

Instantly share code, notes, and snippets.

@kocyigityunus
Last active August 19, 2019 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kocyigityunus/eec1f7a0a2ed6767c1d8cc82dc631051 to your computer and use it in GitHub Desktop.
Save kocyigityunus/eec1f7a0a2ed6767c1d8cc82dc631051 to your computer and use it in GitHub Desktop.
String + CharacterSet Examples
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