How to find out if letter is Alphanumeric or Digit in Swift

后端 未结 4 549
攒了一身酷
攒了一身酷 2020-11-30 05:39

I want to count the number of letters, digits and special characters in the following string:

let phrase = \"The final score was 32-31!\"

I

4条回答
  •  自闭症患者
    2020-11-30 06:01

    I've created a short extension for letter and digits count for a String

    extension String {
      var letterCount : Int {
        return self.unicodeScalars.filter({ CharacterSet.letters.contains($0) }).count
      }
    
      var digitCount : Int {
       return self.unicodeScalars.filter({ CharacterSet.decimalDigits.contains($0) }).count
      }
    }
    

    or a function to get a count for any CharacterSet you put in

    extension String {    
      func characterCount(for set: CharacterSet) -> Int {
        return self.unicodeScalars.filter({ set.contains($0) }).count
      }
    }
    

    usage:

    let phrase = "the final score is 23-13!"
    let letterCount = phrase.characterCount(for: .letters)
    

提交回复
热议问题