i need to get sum of vowels from list of strings with help function .fold
i tried:
val student = listOf("Sheldon", "Leonard", "Howard", "Raj", "Penny", "Amy", "Bernadette")
val vowels = setOf('a','A','e','E','i','I','o','O','y','Y','u','U')
val sumVowels = student.fold(0){acc, student, ->
if(student.contains(vowels)) acc 1 else acc 0
I don't know how to place vowels in .contains. Maybe I choose not the right way to solve the problem, but I should use fold
anyway
CodePudding user response:
val list = listOf("Sheldon", "Leonard", "Howard", "Raj", "Penny", "Amy", "Bernadette")
val vowels = setOf('a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'y', 'Y', 'u', 'U')
val result = list
.joinToString("")
.count { char -> char in vowels }
println(result) // Output: 16
CodePudding user response:
you can write
val sumVowels = student.fold(0){acc, s -> acc s.count{it in vowels}}