Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting how many times specific character appears in string - Kotlin

Tags:

kotlin

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?

like image 941
reducing activity Avatar asked Oct 18 '25 19:10

reducing activity


1 Answers

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.

like image 176
rost Avatar answered Oct 21 '25 00:10

rost



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!