Kotlin Training Program

DOWNLOAD APP

FEEDBACK

Equality check

We have equals() function to check complete equality of two strings. For partial equality, we have startsWith() and endsWith() functions.

 fun main() {
    println("Sun".equals("sun", ignoreCase = true)) // Prints true
    println("Swami Vivekananda".startsWith("Swami")) // Prints true
    println("Bhagat Singh".endsWith("Singh")) // Prints true
}
 

All three functions are similar, the only difference being where to start & end the string comparisons.

Length check at the beginning will save us from unnecessary comparisons.

Implementations

 fun String.equals(other: String, ignoreCase: Boolean = false): Boolean {
    // Return false if lengths don't match
    if (length != other.length) return false

    // Iterate and check each char
    for (i in indices) {

        // Continue if found equal
        if (this[i].equals(other[i], ignoreCase)) continue

        // otherwise (unequal), return false
        return false
    }

    // If we reach here, then both strings are equal
    return true
}

fun String.startsWith(prefix: String, ignoreCase: Boolean = false): Boolean {

    // If length is less than prefix length, return false
    if (this.length < prefix.length) return false

    // Iterate over prefix.length characters
    for (i in prefix.indices) {

        // If equal, continue
        if (this[i].equals(prefix[i], ignoreCase)) continue

        // Otherwise (unequal), return false
        return false
    }

    // If we reach here, then string has given prefix
    return true
}

fun String.endsWith(suffix: String, ignoreCase: Boolean = false): Boolean {

    // If length is less than suffix length, return false
    if (this.length < suffix.length) return false

    // Iterate over suffix.length characters
    for (i in suffix.indices) {

        // If equal, continue
        if (this[lastIndex - suffix.lastIndex + i].equals(suffix[i], ignoreCase)) continue

        // Otherwise (unequal), return false
        return false
    }

    // If we reach here, then string has given prefix
    return true
}
 

For startsWith() and endsWith(), we can use substring approach also, wherein we extract out the required substring and match it against the other string :

 fun String.startsWithUsingSubstring(prefix: String, ignoreCase: Boolean = false): Boolean {

    // If length is less than prefix length, return false
    if (this.length < prefix.length) return false

    // Check exact length substring equality
    return substring(endIndex = prefix.length).equals(prefix, ignoreCase)
}

fun String.endsWithUsingSubstring(suffix: String, ignoreCase: Boolean = false): Boolean {

    // If length is less than suffix length, return false
    if (this.length < suffix.length) return false

    // Check exact length substring equality
    return substring(length - suffix.length).equals(suffix, ignoreCase)
}