How to Determine If a String Contains a Character from a Set in Swift

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")
}

check if string contains anything outside of the character set swift

Here is a simple solution, Just use NSCharacterSet like this :-

let name1="myname" // Input
let characterSet: NSMutableCharacterSet = NSMutableCharacterSet.alphanumericCharacterSet()
characterSet.addCharactersInString("_-.")
name1.stringByTrimmingCharactersInSet(characterSet).isEmpty // If this return true, you enetered the right charcters

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.

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.

Swift 4: Using Swift.contains to check existence of a Character in a String

You first need to understand the concept of "passing a closure to a method" because that is exactly what is happening in the second line.

String.contains can accept a closure of the type Character -> Bool. It will apply the closure on each character of the string and see what it returns. If the closure, when applied to any of the characters, returns true, then contains returns true. Otherwise, false.

This is the closure you are passing in:

{"aeiou".contains($0)}

$0 means the first argument. It checks if the character passed in is one of aeiou. So imagine this closure gets applied to each character in the string to test, and when that returns true, contains returns true.

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")
}

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: 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).")
}


Related Topics



Leave a reply



Submit