Is there a function that checks if a character in a string is a letter in the alphabet? (Swift)
Xcode 8 beta4 • Swift 3
extension String {
var lettersOnly: String {
return components(separatedBy: CharacterSet.letters.inverted).joined(separator:"")
}
var lettersArray: [Character] {
return Array(lettersOnly.characters)
}
}
Xcode 7.3.1 • Swift 2.2.1
extension String {
var lettersOnly: String {
return componentsSeparatedByCharactersInSet(NSCharacterSet.letterCharacterSet().invertedSet).joinWithSeparator("")
}
var lettersArray: [Character] {
return Array(lettersOnly.characters)
}
}
Swift 1.x
import UIKit
extension String {
var lettersOnly: String {
return "".join(componentsSeparatedByCharactersInSet(NSCharacterSet.letterCharacterSet().invertedSet))
}
var lettersArray: [Character] {
return Array("".join(componentsSeparatedByCharactersInSet(NSCharacterSet.letterCharacterSet().invertedSet)))
}
}
let word = "hello 123"
let letters = word.lettersOnly // "hello"
let lettersArray = word.lettersArray // ["h", "e", "l", "l", "o"]
How can I check if a string contains letters in Swift?
You can use NSCharacterSet
in the following way :
let letters = NSCharacterSet.letters
let phrase = "Test case"
let range = phrase.rangeOfCharacter(from: characterSet)
// range will be nil if no letters is found
if let test = range {
println("letters found")
}
else {
println("letters not found")
}
Or you can do this too :
func containsOnlyLetters(input: String) -> Bool {
for chr in input {
if (!(chr >= "a" && chr <= "z") && !(chr >= "A" && chr <= "Z") ) {
return false
}
}
return true
}
In Swift 2:
func containsOnlyLetters(input: String) -> Bool {
for chr in input.characters {
if (!(chr >= "a" && chr <= "z") && !(chr >= "A" && chr <= "Z") ) {
return false
}
}
return true
}
It's up to you, choose a way. I hope this help you.
How to find out if letter is Alphanumeric or Digit in Swift
For Swift 5 see rustylepord's answer.
Update for Swift 3:
let letters = CharacterSet.letters
let digits = CharacterSet.decimalDigits
var letterCount = 0
var digitCount = 0
for uni in phrase.unicodeScalars {
if letters.contains(uni) {
letterCount += 1
} else if digits.contains(uni) {
digitCount += 1
}
}
(Previous answer for older Swift versions)
A possible Swift solution:
var letterCounter = 0
var digitCount = 0
let phrase = "The final score was 32-31!"
for tempChar in phrase.unicodeScalars {
if tempChar.isAlpha() {
letterCounter++
} else if tempChar.isDigit() {
digitCount++
}
}
Update: The above solution works only with characters in the ASCII character set,
i.e. it does not recognize Ä, é or ø as letters. The following alternative
solution uses NSCharacterSet
from the Foundation framework, which can test characters
based on their Unicode character classes:
let letters = NSCharacterSet.letterCharacterSet()
let digits = NSCharacterSet.decimalDigitCharacterSet()
var letterCount = 0
var digitCount = 0
for uni in phrase.unicodeScalars {
if letters.longCharacterIsMember(uni.value) {
letterCount++
} else if digits.longCharacterIsMember(uni.value) {
digitCount++
}
}
Update 2: As of Xcode 6 beta 4, the first solution does not work anymore, because
the isAlpha()
and related (ASCII-only) methods have been removed from Swift.
The second solution still works.
Check if a String is alphanumeric in Swift
extension String {
var isAlphanumeric: Bool {
return !isEmpty && range(of: "[^a-zA-Z0-9]", options: .regularExpression) == nil
}
}
"".isAlphanumeric // false
"abc".isAlphanumeric // true
"123".isAlphanumeric // true
"ABC123".isAlphanumeric // true
"iOS 9".isAlphanumeric // false
What is the best way to determine if a string contains a character from a set in Swift
You can create a CharacterSet
containing the set of your custom characters
and then test the membership against this character set:
Swift 3:
let charset = CharacterSet(charactersIn: "aw")
if str.rangeOfCharacter(from: charset) != nil {
print("yes")
}
For case-insensitive comparison, use
if str.lowercased().rangeOfCharacter(from: charset) != nil {
print("yes")
}
(assuming that the character set contains only lowercase letters).
Swift 2:
let charset = NSCharacterSet(charactersInString: "aw")
if str.rangeOfCharacterFromSet(charset) != nil {
print("yes")
}
Swift 1.2
let charset = NSCharacterSet(charactersInString: "aw")
if str.rangeOfCharacterFromSet(charset, options: nil, range: nil) != nil {
println("yes")
}
How to check whether String only consists of letters and spaces in Swift 5?
let lettersAndSpacesCharacterSet = CharacterSet.letters.union(.whitespaces).inverted
let testValid1 = "Jon Doe".rangeOfCharacter(from: lettersAndSpacesCharacterSet) == nil // true
let testInvalid1 = "Ben&Jerry".rangeOfCharacter(from: lettersAndSpacesCharacterSet) == nil // false
let testInvalid2 = "Peter2".rangeOfCharacter(from: lettersAndSpacesCharacterSet) == nil // false
Iterate through alphabet in Swift
In Swift, you can iterate chars on a string like this:
Swift 2
for char in "abcdefghijklmnopqrstuvwxyz".characters {
println(char)
}
Swift 1.2
for char in "abcdefghijklmnopqrstuvwxyz" {
println(char)
}
There might be a better way though.
How to check if Swift string contains only certain characters?
Use
if string.range(of: "^[a-zA-Z0-9]*$", options: .regularExpression) != nil
as mentioned by @sulthan.
^
is the starting point of regex. This does not match any
character. For example, ^P is regex matching letter P at the
beginning of the String*
Regex followed by * will handle repetition in a regex. For
example P* Matches PPP or P. This will matches the empty string also.$
is the end of the string. This does not match any
character. For example, P$ regex will match P at the end of the string.
Use +
instead of *
if you want to avoid empty string. "^[a-zA-Z0-9]+$"
as mentioned by vadian
Check if a string contains at least a upperCase letter, a digit, or a special character in Swift?
Simply replace your RegEx rule [A-Z]+ with .*[A-Z]+.* (and other RegEx rules as well)
Rules
[A-Z]+ matches only strings with all characters capitalized
Examples: AVATAR, AVA, TAR, AAAAAA
Won't work: AVATAr
.* matches all strings (0+ characters)
Examples: 1, 2, AVATAR, AVA, TAR, a, b, c
.*[A-Z]+.* matches all strings with at least one capital letter
Examples: Avatar, avataR, aVatar
Explanation:
I. .* will try to match 0 or more of anything
II. [A-Z]+ will require at least one capital letter (because of the +)
III. .* will try to match 0 or more of anything
Avatar [empty | "A" | "vatar"]
aVatar ["a" | "V" | "atar"]
aVAtar ["a" | "VA" | "tar"]
Working Code
func checkTextSufficientComplexity(var text : String) -> Bool{
let capitalLetterRegEx = ".*[A-Z]+.*"
var texttest = NSPredicate(format:"SELF MATCHES %@", capitalLetterRegEx)
var capitalresult = texttest!.evaluateWithObject(text)
println("\(capitalresult)")
let numberRegEx = ".*[0-9]+.*"
var texttest1 = NSPredicate(format:"SELF MATCHES %@", numberRegEx)
var numberresult = texttest1!.evaluateWithObject(text)
println("\(numberresult)")
let specialCharacterRegEx = ".*[!&^%$#@()/]+.*"
var texttest2 = NSPredicate(format:"SELF MATCHES %@", specialCharacterRegEx)
var specialresult = texttest2!.evaluateWithObject(text)
println("\(specialresult)")
return capitalresult || numberresult || specialresult
}
Examples:
checkTextSufficientComplexity("Avatar") // true || false || false
checkTextSufficientComplexity("avatar") // false || false || false
checkTextSufficientComplexity("avatar1") // false || true || false
checkTextSufficientComplexity("avatar!") // false || false || true
Related Topics
Python: Binding Socket: "Address Already in Use"
Python Parse CSV Ignoring Comma with Double-Quotes
Is This Bad Programming Practice in Tkinter
Display a 'Loading' Message While a Time Consuming Function Is Executed in Flask
Python How to Parse CSS File as Key Value
Fama MACbeth Regression in Python (Pandas or Statsmodels)
Learning Python from Ruby; Differences and Similarities
Python Equivalent of Ruby's .Select
Looking for Recommendation on How to Convert PDF into Structured Format
How to Convert a Dictionary into a List of Tuples
How to Pass Optional Parameters to a Function
How to Capture Multiple Camera Streams with Opencv
Python MySQL Connector Database Query with %S Fails
Django: Redirect to Previous Page After Login
What Makes Sets Faster Than Lists