Kotlin String.get()

Kotlin String.get() Tutorial

The String.get() function in Kotlin is used to retrieve the character at a specified index within a string.

Strings in Kotlin are zero-indexed, meaning the index of the first character is 0, the second character is at index 1, and so on.

In this tutorial, we’ll explore the syntax of the String.get() function and provide examples of its usage in Kotlin strings.

Syntax

The syntax of the String.get() function is as follows:

fun String.get(index: Int): Char

where

ParameterDescription
indexAn integer value representing the position of the character we are interested in.
Parameters of String.get() function

The String.get() function returns the character at specified index as Char value.

Examples for String get() function

1. Retrieving Characters by Index

Kotlin Program

fun main() {
    val myString = "Hello, World!"

    // Using get() to retrieve character at index=9
    val index = 9
    val characterAtIndex = myString.get(index)

    // Printing the original string and the retrieved character
    println("Original String:\n$myString\n")
    println("Character at Index=$index:\n$characterAtIndex")
}

Output

Original String:
Hello, World!

Character at Index=9:
r

Explanation

H e l l o ,   W o r  l  d  !
0 1 2 3 4 5 6 7 8 9 10 11 12
                  ↑
           char at index=9

Summary

In this tutorial, we’ve covered the get() function in Kotlin strings, its syntax, and how to use it to retrieve characters at specified indices within a string.