Kotlin Training Program

DOWNLOAD APP

FEEDBACK

Trim

To remove few characters from start or end of a string, we can use the trim() function :

 fun main() {
    val name = "\t  Lady Ada Lovelace    "

    println(name.trim())        // Prints "Lady Ada Lovelace"
    println(name.trimStart())   // Prints "Lady Ada Lovelace    "
    println(name.trimEnd())     // Prints "	  Lady Ada Lovelace"

		val string = "*-*-* GOLD *-*-*"

    println(
        string.trim {
            it in listOf('*', '-', ' ') // Removes all 3 characters
        }
    ) // Prints "GOLD"
}
 

The function takes a predicate lambda which returns true for the character to be removed.

The major task in trimming a string is to find out the first and last index of the required string. Once we have the indices, we can extract the substring out.

Algorithm

Implementation

 fun String.trim(
    predicate: (Char) -> Boolean = Char::isWhitespace
): String {

    // Find the firstIndex
    var firstIndex = 0
    for (i in indices) {
        firstIndex = i
        if (!predicate(get(i))) break
    }

    // Find the lastIndex
    var lastIndex = lastIndex
    for (i in indices.reversed()) {
        lastIndex = i
        if (!predicate(get(i))) break
    }

    // Check Entire string full of not required characters
    if (lastIndex < firstIndex) return ""

    // Extract and return the required substring
    return substring(firstIndex, lastIndex + 1)
}