How to Check If a String Contains Letters in Swift

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 do I check if a string contains another string in Swift?

You can do exactly the same call with Swift:

Swift 4 & Swift 5

In Swift 4 String is a collection of Character values, it wasn't like this in Swift 2 and 3, so you can use this more concise code1:

let string = "hello Swift"
if string.contains("Swift") {
print("exists")
}

Swift 3.0+

var string = "hello Swift"

if string.range(of:"Swift") != nil {
print("exists")
}

// alternative: not case sensitive
if string.lowercased().range(of:"swift") != nil {
print("exists")
}

Older Swift

var string = "hello Swift"

if string.rangeOfString("Swift") != nil{
println("exists")
}

// alternative: not case sensitive
if string.lowercaseString.rangeOfString("swift") != nil {
println("exists")
}

I hope this is a helpful solution since some people, including me, encountered some strange problems by calling containsString().1

PS. Don't forget to import Foundation

Footnotes

  1. Just remember that using collection functions on Strings has some edge cases which can give you unexpected results, e. g. when dealing with emojis or other grapheme clusters like accented letters.

Swift: Check if String contains Character?

string.contains(character)

Example:

let string = "Hello, World!"
let character: Character = "e"

if string.contains(character) {
print("\(string) contains \(character).")
} else {
print("\(string) doesn't contain \(character).")
}

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

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 if Swift string contains only certain characters?

Use

if string.range(of: "^[a-zA-Z0-9]*$", options: .regularExpression) != nil as mentioned by @sulthan.

  1. ^ 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

  2. * Regex followed by * will handle repetition in a regex. For
    example P* Matches PPP or P. This will matches the empty string also.

  3. $ 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

Swift – How to find out if a string contains several identical characters?

You can use filter(_:) on the string and count to get the number of dots:

let str = "3..14"

switch str.filter({ $0 == "." }).count {
case 0:
print("string has no dots")
case 1:
print("string has 1 dot")
default:
print("string has 2 or more dots")
}

Check if string contains special characters in Swift

Your code check if no character in the string is from the given set.
What you want is to check if any character is not in the given set:

if (searchTerm!.rangeOfCharacterFromSet(characterSet.invertedSet).location != NSNotFound){
println("Could not handle special characters")
}

You can also achieve this using regular expressions:

let regex = NSRegularExpression(pattern: ".*[^A-Za-z0-9].*", options: nil, error: nil)!
if regex.firstMatchInString(searchTerm!, options: nil, range: NSMakeRange(0, searchTerm!.length)) != nil {
println("could not handle special characters")

}

The pattern [^A-Za-z0-9] matches a character which is not from the ranges A-Z,
a-z, or 0-9.

Update for Swift 2:

let searchTerm = "a+b"

let characterset = NSCharacterSet(charactersInString: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
if searchTerm.rangeOfCharacterFromSet(characterset.invertedSet) != nil {
print("string contains special characters")
}

Update for Swift 3:

let characterset = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
if searchTerm.rangeOfCharacter(from: characterset.inverted) != nil {
print("string contains special characters")
}


Related Topics



Leave a reply



Submit