Kotlin: count occurrences of `charArray` in `String`

You can use the below higher order method,

val count = string2.count{ string1.contains(it) }
print(count)

Here are some String extension functions you can use

Occurrences of any char

With the fold extension function:

val string1 = "Hello"
val string2 = "Hello world Hello"

print(
     string2.fold(0) {
         sum: Int, c: Char ->
         if (string1.contains(c))
             sum + 1
         else
             sum
     }   
) 

Or even shorter with sumBy:

string2.sumBy { 
    if (string1.contains(it))
        1
    else
        0
}

And shortest:

string2.count{ string1.contains(it) }

Occurrences of each char individually

With forEach and a MutableMap:

val charsMap = mutableMapOf<Char, Int>()

string2.forEach{
    charsMap[it] = charsMap.getOrDefault(it, 0) + 1
}

print(charsMap)

Occurrences of the whole string1

With the windowed extension function:

string2.windowed(string1.length){
    if (it.equals(string1))
        1
    else
        0
}.sum()

You can browse more String extension functions in the String stblib page

Tags:

String

Kotlin