Kotlin Training Program

DOWNLOAD APP

FEEDBACK

Substring

To extract a portion of string, we can use the substring() function :

 fun main() {
    println("**--GOLD**".substring(4)) // Prints "GOLD**"
    println("**--GOLD**".substring(4, 8)) // Prints "GOLD"
    println("**--GOLD**".substring(4..7)) // Prints "GOLD"
}
 

To extract the substring, we iterate only through the given indices and use a StringBuilder to form the required string :

 fun String.substring(
    startIndex: Int = 0,
    endIndex: Int = length
): String {
    return buildString {
        for (i in startIndex until endIndex) {
            append(this@substring[i])
        }
    }
}
 

Note that instead of StringBuilder, we can use CharArray also.