Ta3ik
Ta3ik

Reputation: 23

Find matches in different indices in String. Kotlin

I have two lines of the same length. I need to get the number of letters that match as letters and have different index in the string (without nesting loop into loop). How I can do it?

Upvotes: 0

Views: 1178

Answers (1)

Ivo
Ivo

Reputation: 23164

Would the following function work for you?

fun check(s1: String, s2: String): Int {
    var count = 0
    s2.forEachIndexed { index, c -> 
        if (s1.contains(c) && s1[index] != c) count++
    }
    return count
}

See it working here

Edit: Alternatively, you could do it like this if you want a one-liner

val count = s1.zip(s2){a,b -> s1.contains(b) && a != b}.count{it}

where s1 and s2 are the 2 strings

Upvotes: 1

Related Questions