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

后端 未结 4 563
攒了一身酷
攒了一身酷 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:16

    For Swift 5 you can do the following for simple strings, but be vigilant about handling characters like "1️⃣" , "④" these would be treated as numbers as well.

    let phrase = "The final score was 32-31!"
    
    var numberOfDigits = 0;
    var numberOfLetters = 0;
    var numberOfSymbols = 0;
    
    phrase.forEach {
    
        if ($0.isNumber) {
            numberOfDigits += 1;
        }
        else if ($0.isLetter)  {
            numberOfLetters += 1
        }
        else if ($0.isSymbol || $0.isPunctuation || $0.isCurrencySymbol || $0.isMathSymbol) {
            numberOfSymbols += 1;
        }
    }
    
    print(#"\#(numberOfDigits)  || \#(numberOfLetters) || \#(numberOfSymbols)"#);
    

提交回复
热议问题