Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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")     } } 
like image 250
hazrpg Avatar asked Jul 22 '14 09:07

hazrpg


People also ask

How do I know if a string contains white space?

Use the test() method to check if a string contains whitespace, e.g. /\s/. test(str) . The test method will return true if the string contains at least one whitespace character and false otherwise.

How do you check if a string has any characters?

Use the String. includes() method to check if a string contains a character, e.g. if (str. includes(char)) {} . The include() method will return true if the string contains the provided character, otherwise false is returned.

How do you check if a string contains both alphabets and numbers in Python?

Letters can be checked in Python String using the isalpha() method and numbers can be checked using the isdigit() method.

Which method is used to check string contains Whitespaces or not?

containsWhitespace is a static method of the StringUtils class that is used to check whether a string contains any whitespace or not. A character is classified as whitespace with the help of Character. isWhitespace.


1 Answers

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 
like image 197
zaph Avatar answered Oct 20 '22 06:10

zaph