How can I check if a string contains letters in Sw

2019-03-10 22:47发布

问题:

This question already has an answer here:

  • What is the best way to determine if a string contains a character from a set in Swift 9 answers

I'm trying to check whether a specific string contains letters or not.

So far I've come across NSCharacterSet.letterCharacterSet() as a set of letters, but I'm having trouble checking whether a character in that set is in the given string. When I use this code, I get an error stating:

'Character' is not convertible to 'unichar'

For the following code:

for chr in input{
    if letterSet.characterIsMember(chr){
        return "Woah, chill out!"
    }
}

回答1:

You can use NSCharacterSet in the following way :

let letters = NSCharacterSet.letterCharacterSet()

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

// 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.



回答2:

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.



回答3:

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