Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

kotlin

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

like image 671
Anuj TBE Avatar asked Apr 15 '18 20:04

Anuj TBE


People also ask

How do you count specific occurrences of characters in a string?

First, we split the string by spaces in a. Then, take a variable count = 0 and in every true condition we increment the count by 1. Now run a loop at 0 to length of string and check if our string is equal to the word.

How do you count occurrences of substring in a string?

Python String count() The count() method returns the number of occurrences of a substring in the given string.


1 Answers

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

like image 69
stan0 Avatar answered Sep 20 '22 11:09

stan0