Search code examples
stringkotlinmethodscharacterstring-matching

Is there a better way to Count the Number of matching characters in a pair of strings in Kotlin


fun compute(l: String, r: String): Int {
    var counter = 0
    for (i in l.indices) when {
        l[i]!=r[i] -> counter++
    }
    return counter
}

Is there an inbuilt function that can be used instead of looping over every character explicitly?

Assuming

  1. strings have equal length
  2. position of chars matters
  3. comparison is case-sensitive

Solution

  • You can simply do count if the order does not matter:

    return l.count { it in r }
    

    However, if you want to check that the value and the index match, you cannot escape using index:

    l.forEachIndexed { i, it -> 
        if(i < r.length && it == r[i]) counter++ 
    }
    

    UPD: Oh I just found out that there is commonPrefixWith

    return l.commonPrefixWith(r).length