How can I check to see if a string contains characters of whitespace/alphanumeric/etc?
Asked Answered
Q

7

25

How can you use the "ctype.h" library in Swift to be able to use isAlpha or isSpace on characters? Or is there a better, Swift, way of doing it?

This question is answered, but it doesn't seem to work: Swift: how to find out if letter is Alphanumeric or Digit

It doesn't specify how to import the library. Could someone point me in the right direction?

Here's what I've got so far:

extension String {
    subscript (i : Int) -> String {
        return String(Array(self)[i])
    }
}

let whitespace = NSCharacterSet.whitespaceCharacterSet()

let phrase = "Test case"

for var i=0; i<countElements(phrase); i++ {
    if whitespace.characterIsMember(phrase[i]) { //error
        println("char is whitespace")
    }
}
Quan answered 22/7, 2014 at 9:41 Comment(5)
Is it a good idea to use methods that don't support Unicode on Swift strings?Triplane
It seems that the (ASCII-only) functions isAlpha(), isDigit() have been removed from Swift. But the NSCharacterSet-based method from that answer should still work.Nutshell
I'm trying to use that (NSCharacterSet), but it keeps saying "character is not convertible to unichar".Quan
Post your code. Remember how Swift handles automatic conversions between different primitive types?Consumedly
Updated the question with the code I have.Quan
C
36

Use NSCharacter on the entire string,not character-by-character:

let whitespace = NSCharacterSet.whitespaceCharacterSet()

let phrase = "Test case"
let range = phrase.rangeOfCharacterFromSet(whitespace)

// range will be nil if no whitespace is found
if let test = range {
    println("whitespace found")
}
else {
    println("whitespace not found")
}

Output:

whitespace found
Campney answered 22/7, 2014 at 12:9 Comment(0)
V
12

I created a String extension that does exactly this, hope it's useful.

extension String {
    func containsWhitespaceAndNewlines() -> Bool {
        return rangeOfCharacter(from: .whitespacesAndNewlines) != nil
    }
}

// Usage
"hello, world!".containsWhitespaceAndNewlines() // true
"hello,world!".containsWhitespaceAndNewlines() // false
Venepuncture answered 17/11, 2015 at 15:26 Comment(0)
F
11

Shorter extension (swift 4.1)

extension String {
    var containsWhitespace : Bool {
        return(self.rangeOfCharacter(from: .whitespacesAndNewlines) != nil)
    }
}

You can change the .whitespacesAndNewlines with any other CharacterSet like this:

extension String {
    var containsDigits : Bool {
        return(self.rangeOfCharacter(from: CharacterSet.decimalDigits) != nil)
    }
}
Fascism answered 27/3, 2017 at 12:57 Comment(0)
P
3

This answer works with text fields. I was going crazy trying to search for whitespace on a UItextfield without searching the string content of it. This works for UItextfields:

Swift 4:

    if (textField.text?.contains(" "))!{
        print("Has space")
    }else{
        print("Does not have space")
    }

This is for a regular string, also in swift 4

    if string.contains(" "){
        print("Has space")
    }else{
        print("Does not have space")
    }
Pathognomy answered 10/3, 2019 at 19:42 Comment(0)
H
1

For Swift 5

extension String {

    func containsWhiteSpace() -> Bool {

        // check if there's a range for a whitespace
        let range = self.rangeOfCharacter(from: .whitespacesAndNewlines)

        // returns false when there's no range for whitespace
        if let _ = range {
            return true
        } else {
            return false
        }
    }
}
Housewifely answered 7/9, 2019 at 22:15 Comment(0)
E
1

Or you can just use regex:

extension String {
   func isContainWhiteSpace() -> Bool {
       let whiteSpace = "\\s+"
       let predicate = NSPredicate(format: "SELF MATCHES %@", whiteSpace)
       return predicate.evaluate(with: self)
   }
}

Meaning:

"\s" mean Any white space character
"+" mean One or More of character
Notice the double back slash we can't use single back slash as it'll return error: Invalid escape sequence in literal so we need to use double back slash to avoid that error.

Usage:

let sample = " "
print(sample.isContainWhiteSpace() ? "Contain White Space" : "Acceptable White Space")

Note: I use this in case I want to validate when user try to input empty white space, this will prevent user to do so.

Erosive answered 21/2 at 15:24 Comment(0)
C
-1

This function will tell you if there is a whitespace between a string. for example if you are trying to make sure the user enter a first and last name

Swift 5

func validatTextField() -> Bool {
        var isValid = false
        if textField.text!.contains(" ") && !textField.text!.isEmpty{
            let cardHolderChar = textField.text!
            for i in cardHolderChar {
                if i == " " && i == cardHolderChar.last {
                    isValid = false
                }
                else {
                    isValid = true
                }
            }
        }
        return isValid
    }
Circlet answered 28/8, 2021 at 21:7 Comment(1)
How does this answer the question? You haven't provided any commentLoco

© 2022 - 2024 — McMap. All rights reserved.