Kotlin String - indices Property



The Kotlin string indices property is used to return an indices range that represents the valid indices of a string. This range may be used to iterate through the characters of the string or perform operations on specific indices.

Note: The index property reduces the risk of IndexOutOfBoundsException by assuring that we work within the valid bound of string.

This property provides a range from 0 to the last index of the string, i.e., length -1. It is also useful for safe access to all valid indices of the string without explicitly calculating the range.

Syntax

Following is the syntax of the Kotlin string indices property −

val indices: IntRange

Example 1: Display all Characters

This is a basic example. Here, we are taking a string and displaying all characters by iterating through the 'indices' property −

fun main() {
   val str = "tutorialspoint"
   for (i in str.indices) {
      println("Character at index $i: ${str[i]}")
   }
}

Output

Following is the output −

Character at index 0: t
Character at index 1: u
Character at index 2: t
Character at index 3: o
Character at index 4: r
Character at index 5: i
Character at index 6: a
Character at index 7: l
Character at index 8: s
Character at index 9: p
Character at index 10: o
Character at index 11: i
Character at index 12: n
Character at index 13: t

Example 2: Print the Range of String

Let's see another example of the indices property here we print the range of the string −

fun main() {
   val str = "this is tutorialspoint"
   val range = str.indices
   println("Range of the string: " + range)
}

Output

Following is the output −

Range of the string: 0..21

Example 3: Filter Based on Indices

The below example demonstrates how to perform filtering based on indices −

fun main() {
   val str = "tutorialspoint!"
   val evenIndexChars = str.indices.filter { it % 2 == 0 }.map { str[it] }
   println(evenIndexChars)
}

Output

Following is the output −

[t, t, r, a, s, o, n, !]
kotlin_strings.htm
Advertisements