Joseph Jude

Technology, Psychology, and Story Telling

Swift Challenge 009: Count upper and lower case letters in a string

Posted: Tags: code,swift

Challenge: Write a program to count upper and lower case letters in a given string.

Test Cases:

  • Hello World should return 2 & 8
  • Hello 123 World $# should also return 2 & 8

Logic:

  • Swift doesn't have any string functions to identify upper or lower case characters
  • So write extensions to identify upper and lower case characters
  • Use regular expressions & rangeOfString to identify upper and lower case characters

Code:

import Foundation 

extension Character {
  func isUpper() -> Bool {    
    if String(self).rangeOfString("[A-Z]", options: .RegularExpressionSearch) != nil {
      return true
    }
     return false
  }
}

extension Character {
  func isLower() -> Bool {
    if String(self).rangeOfString("[a-z]", options: .RegularExpressionSearch) != nil {
      return true
    }
     return false
  }
}

let inputString = "Hello @World [email protected]"
var (upper,lower) = (0,0)

for c in inputString.characters {
  if c.isUpper() {
    upper += 1
  }
  
  if c.isLower() {
    lower += 1
  }
}

print(upper, lower)

Git Repository / All Swift Challenges

Got comments? Tweet it, or comment below.



Like the post? Retweet it. Got comments? Reply.

Comments

comments powered by Disqus