如何在kotlin中获取列表中的元音总和
how to get sum of vowels in list in kotlin
我需要使用帮助函数 .fold
从字符串列表中获取元音总和
我试过了:
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
我不知道如何在 .contains 中放置元音。也许我选择了不正确的方法来解决问题,但我还是应该使用fold
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
你可以写
val sumVowels = student.fold(0){acc, s -> acc + s.count{it in vowels}}
我需要使用帮助函数 .fold
从字符串列表中获取元音总和我试过了:
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
我不知道如何在 .contains 中放置元音。也许我选择了不正确的方法来解决问题,但我还是应该使用fold
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
你可以写
val sumVowels = student.fold(0){acc, s -> acc + s.count{it in vowels}}