Joseph Jude

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

2016.01.06 / code / swift /

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

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

Test Cases:

Logic:

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.


Share this post on

Twitter | | |