Kotlin String lastIndex

Kotlin String lastIndex Property Tutorial

The lastIndex property of String class in Kotlin is used to obtain the index of the last character in a string.

In this tutorial, we’ll explore the lastIndex property and provide examples of its usage in Kotlin strings.


The syntax of lastIndex property is

val CharSequence.lastIndex: Int


The lastIndex property is a member of the String class and can be accessed on any string object.

val lastCharIndex: Int = yourString.lastIndex

The lastIndex property returns the index of the last character in the string. This index is equal to the length of the string minus one.

Example for String lastIndex Property

In this example, we take a string in myString, and get the index of last character in the string using lastIndex property.

Kotlin Program

fun main() {
    val kotlinString = "Hello, Kotlin!"

    // Obtaining the index of the last character
    val lastCharIndex: Int = kotlinString.lastIndex

    // Printing the original string and the last character index
    println("Input String:\n$kotlinString\n")
    println("Last Character Index:\n$lastCharIndex")


Input String:
Hello, Kotlin!

Last Character Index:


In this tutorial, we’ve covered the lastIndex property in Kotlin strings, its usage, and how to obtain the index of the last character. This property is useful when you need to reference or perform operations specifically on the last character of a string.