Created
April 24, 2019 15:17
-
-
Save mredig/f6606a621a7b20c12b007cccb3061154 to your computer and use it in GitHub Desktop.
vowel counter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
This will count and return the number of vowels in a string. Vowels are defined as "a, e, i, o, and u" and sometimes "y"! | |
("y" is only counted when there's no other vowel in a word. A word is defined as a string of characters between spaces). | |
*/ | |
func numberOfVowels(in string: String) -> Int { | |
let vowels: Set<Character> = ["a", "e", "i", "o", "u"] | |
let string = string.lowercased() | |
let words = string.split(separator: " ") | |
var totalCount = 0 | |
for word in words { | |
var wordVowelCount = 0 | |
for letter in word { | |
if vowels.contains(letter) { | |
wordVowelCount += 1 | |
} | |
} | |
// and sometimes "y"! | |
if wordVowelCount == 0 { | |
for letter in word { | |
if letter == "y" { | |
wordVowelCount += 1 | |
} | |
} | |
} | |
totalCount += wordVowelCount | |
} | |
return totalCount | |
} | |
print(numberOfVowels(in: "Hello World!")) // 3 | |
print(numberOfVowels(in: "I have a lovely bunch of coconuts!")) // 11 | |
print(numberOfVowels(in: "My")) // 1 | |
print(numberOfVowels(in: "My goodness!")) // 4 | |
print(numberOfVowels(in: "Lambda is really neat.")) // 7 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment