I have two strings
val string1 = "Hello"
val string2 = "Hello world"
I have to count existence of each letter from string1
in string2
in Kotlin
So far, I have written this much code and stuck with regex
val string1_array = string1.toCharArray()
val pattern = Regex("") // Regex pattern here
val matcher = string2
val count = pattern.findAll(matcher).count()
What should be the appropriate Regex pattern to search for charArray? Is there some better way to do in Kotlin
Best Answer
Here are some
String
extension functions you can useOccurrences of any char
With the
fold
extension function:Or even shorter with
sumBy
:And shortest:
Occurrences of each char individually
With
forEach
and aMutableMap
:Occurrences of the whole
string1
With the
windowed
extension function:You can browse more
String
extension functions in theString
stblib page