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

半城伤御伤魂 提交于 2019-12-03 06:48:08

问题


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




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


来源:https://stackoverflow.com/questions/29520618/how-can-i-check-if-a-string-contains-letters-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!