Kotlin String indices property

Kotlin String indices Property Tutorial

The indices property in Kotlin is used to obtain the range of valid indices for the characters in a string.

This tutorial will explore the indices property and provide examples of its usage in Kotlin strings.

Syntax

The syntax of indices property is

val CharSequence.indices: IntRange

Usage

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

val charIndices: IntRange = yourString.indices

The indices property returns an IntRange, which represents the valid range of indices for the characters in the string. This range includes the index of the first character (0) and goes up to the index of the last character (string length – 1).

Example for String indices Property

In this example, we take a string in myString, and get the range of indices for this string.

Kotlin Program

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

    // Obtaining the indices range
    val charIndices: IntRange = myString.indices

    // Printing the original string and the indices range
    println("Input String:\n$myString\n")
    println("Indices Range:\n$charIndices")
}

Output

Input String:
Hello, World!

Indices Range:
0..12

You may iterate over the indices range using a For loop, as shown in the following.

Kotlin Program

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

    for (i in myString.indices) {
        println(i)
    }
}

Output

0
1
2
3
4
5
6
7
8
9
10
11
12

Summary

In this tutorial, we’ve covered the indices property in Kotlin strings, its usage, and how to obtain the range of valid indices for the characters. This property is helpful when you need to iterate over the characters of a string or perform operations based on their indices.