DEV Community

Discussion on: Daily Challenge #219 - Compare Strings

Collapse
 
olegthelilfix profile image
Oleg Aleksandrov • Edited

Kotlin.

fun strCount(str1: String, str2: String): Int {
    var count = 0
    var matchIndex = 0
    var i = 0
    var indexOfFirstMatch = 0

    while (i < str1.length) {
        if (str1[i] == str2[matchIndex]) {
            if (matchIndex == 0) {
                indexOfFirstMatch = i
            }

            if ((++matchIndex) == str2.length) {
                count++
                matchIndex = 0
                i = indexOfFirstMatch + 1
            }
            else {
                i++
            }
        }
        else {
            i++
            matchIndex = 0
        }
    }

    return count
}

fun main() {
    println(strCount("Hello", "o"))
    println(strCount("Hello", "l"))
    println(strCount("", "z"))
    println(strCount("oh goodness gracious", "o"))
    println(strCount("howdy, pardner", "d"))
    println(strCount("Incumbent President", "e"))
 // also it's fine too
    println(strCount("Hello helllo", "ll"))
    println(strCount("eeeeeee", "ee"))
}