Skip to content

Sum of two index in array & its index

Code

func calculateNoOfVowelsAndConsonants(in string: String) -> (vowels: Int, consonants: Int) {
    let vowelsSet: Set<Character> = ["a", "e", "i", "o", "u"]
    var vowelCount = 0
    var consonantCount = 0

    for char in string.lowercased() {
        if vowelsSet.contains(char) {
            vowelCount += 1
        } else if char.isLetter {
            consonantCount += 1
        }
    }

    return (vowels: vowelCount, consonants: consonantCount)
}

Example

// Example usage
let inputString = "Hello World"
let counts = calculateNoOfVowelsAndConsonants(in: inputString)

print("Number of vowels: \(counts.vowels)")
print("Number of consonants: \(counts.consonants)")

Output

Number of vowels: 3
Number of consonants: 7