-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
  • 55,661
  • 11
  • 60
  • 99
oooparkh
  • 19
  • 1
  • 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
  • 1,892
  • 1
  • 6
  • 16
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
  • 6,881
  • 3
  • 19
  • 32
1

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,823
  • 3
  • 30
  • 39
-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)