reducing activity
reducing activity

Reputation: 2254

Counting how many times specific character appears in string - 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?

Upvotes: 3

Views: 1631

Answers (1)

rost
rost

Reputation: 4077

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.

Upvotes: 3

Related Questions