How can I check if a string contains letters in Swift? [duplicate]

好久不见. 提交于 2019-12-02 20:27:57
Victor Sigler

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.

You should use the Strings built in range functions with NSCharacterSet rather than roll your own solution. This will give you a lot more flexibility too (like case insensitive search if you so desire).

let str = "Hey this is a string"
let characterSet = NSCharacterSet(charactersInString: "aeiou")

if let _ = str.rangeOfCharacterFromSet(characterSet, options: .CaseInsensitiveSearch) {
    println("true")
}
else {
    println("false")
}

Substitute "aeiou" with whatever letters you're looking for.

A less flexible, but fun swift note all the same, is that you can use any of the functions available for Sequences. So you can do this:

contains("abc", "c")

This of course will only work for individual characters, and is not flexible and not recommended.

The trouble with .characterIsMember is that it takes a unichar (a typealias for UInt16).

If you iterate your input using the utf16 view of the string, it will work:

let set = NSCharacterSet.letterCharacterSet()
for chr in input.utf16 {
    if set.characterIsMember(chr) {
        println("\(chr) is a letter")
    }
}

You can also skip the loop and use the contains algorithm if you only want to check for presence/non-presence:

if contains(input.utf16, { set.characterIsMember($0) }) {
    println("contains letters")
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!