Home > other >  Counting how many times specific character appears in string - Kotlin
Counting how many times specific character appears in string - Kotlin

Time:10-29

How one may count how many times specific character appears in string in Kotlin?

From looking at https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/ there is nothing built-in and one needs to write loop every time (or may own extension function), but maybe I missed a better way to achieve this?

CodePudding user response:

Easy with filter {} function

val str = "123 123 333"

val countOfSymbol = str
        .filter { it == '3' } // 3 is your specific character
        .length

println(countOfSymbol) // output 5

Another approach

val countOfSymbol = str.count { it == '3'} // 3 is your specific character
println(countOfSymbol) // output 5

From the point of view of saving computer resources, the count decision(second approach) is more correct.

  • Related