【问题标题】:how to get sum of vowels in list in kotlinhow to get sum of vowels in list in kotlin
【发布时间】:2022-12-27 22:17:15
【问题描述】:

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

【问题讨论】:

    标签: list kotlin contains fold


    【解决方案1】:
    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
    

    【讨论】:

    • While this is good code*, it doesn't strictly answer the question, which asked for a solution using fold(). (* Actually, I think I prefer the slightly more complex but more memory-efficient approach of list.sumOf{ it.count{ it in vowels }}.)
    【解决方案2】:

    you can write

    val sumVowels = student.fold(0){acc, s -> acc + s.count{it in vowels}}
    

    【讨论】:

      【解决方案3】:
      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')
      var numberOfVowels = 0
      list.forEach{s ->
         numberOfVowels += s.count{it in vowels}
      }
      println(numberOfVowels)
      
      Output: 16
      

      【讨论】:

        猜你喜欢
        • 2022-12-02
        • 1970-01-01
        • 2022-12-16
        • 2022-12-27
        • 2022-12-01
        • 2022-12-27
        • 2022-12-02
        • 2022-12-01
        • 2022-12-02
        相关资源
        最近更新 更多