1

How can I count the quantity of lowercase and uppercase letters in string?

For example:

Input:

Hello World

Output:

8 2

Because the input contains 8 lowercase, and 2 uppercase letters.

cigien
  • 57,834
  • 11
  • 73
  • 112
oooparkh
  • 39
  • 2
  • 1
    Does this answer your question? [How can I identify uppercase and lowercase characters in a string with swift?](https://stackoverflow.com/questions/24268690/how-can-i-identify-uppercase-and-lowercase-characters-in-a-string-with-swift) – mcd Jan 10 '21 at 21:36
  • 1
    What should happen with white-space, symbols and other non-alphabet characters? – Braiam Jan 11 '21 at 13:01

4 Answers4

2

You could use the built-in functionality of Character by using it's isUppercase and isLowercase attributes:

var str = "Hello, playground"

var numOfUppercasedLetters = 0
var numOfLowercasedLetters = 0

for char in str {
    if char.isUppercase {
        numOfUppercasedLetters += 1
    } else if char.isLowercase {
        numOfLowercasedLetters += 1
    }
}

print(numOfUppercasedLetters, numOfLowercasedLetters)

See this thread for further information: How can I identify uppercase and lowercase characters in a string with swift?

finebel
  • 2,227
  • 1
  • 9
  • 20
2

You can just use reduce(_:_:) function of String like this:

var string = "Hello"

let (uppercase, lowercase) = string.reduce((0, 0)) { (result, character) -> (Int, Int) in
    if character.isUppercase {
        return (result.0 + 1, result.1)
    } else if character.isLowercase {
        return (result.0, result.1 + 1)
    }
    return result
}

print(uppercase, lowercase)
gcharita
  • 7,729
  • 3
  • 20
  • 37
2

I don't know exactly from which version of Swift the following code compiles, but I tested it with Swift 5.4:

import Foundation

let testString = "ABCdefg"

let lowercase = testString.filter { $0.isLowercase }.count
let uppercase = testString.filter { $0.isUppercase }.count

print(lowercase, uppercase)
asclepix
  • 7,971
  • 3
  • 31
  • 41
-1
import Foundation

let  testString = "ABCdefg"
var uppercase = 0;
var lowercase = 0;

for character in testString {
    if character.isUppercase {
        uppercase += 1
    } else {
        lowercase += 1
    }
}

print(uppercase)
print(lowercase)