CodeBlanks Logo Icon CodeBlanks

substring

Learn to take parts of a string with substring.

substring

To take a part of a String, use substring(startIndex, endIndex). startIndex is inclusive, endIndex is exclusive.

val s = "Kotlin"
println(s.substring(0, 3))  // Kot
println(s.substring(2, 5))  // tli

Indices start at 0. substring(0, 3) takes characters at 0, 1 and 2; that is the first three letters. The String's length is a safe endIndex.

A single-argument substring(startIndex) also exists; it takes from that index to the end.

Practice Take the first and last three letters

Write a fun main(). Assign "Kotlin" to val lang. Print lang.substring(0, 3) for the first three letters and lang.substring(3, 6) for the last three on separate lines.

Starter code

Main.kt
fun main() {
    // Take the first and last three letters
}

Sample solution

Main.kt
fun main() {
    val lang = "Kotlin"
    println(lang.substring(0, 3))
    println(lang.substring(3, 6))
}

Expected output

Kot
lin

substring with one argument

substring(startIndex) takes one argument and returns the part from that index to the end of the String.

val s = "Kotlin"
println(s.substring(3))  // lin

From index 3 to the end: lin. This is the same as substring(3, s.length) but shorter.

In the two-argument form, endIndex cannot be smaller than startIndex; otherwise IndexOutOfBoundsException is thrown.

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the substring call

Question
val part = s.____(0, 3)
Answer
val part = s.substring(0, 3)

Explanation: s.substring(0, 3) takes the first three characters.

2 What does "Kotlin".substring(2, 5) return?

  • tli Correct answer
  • Kot
  • tlin
  • in

Explanation: Indices 2, 3, 4 give tli.

3 Match the substring results

Term Meaning
substring(0, 3) of "Kotlin" Kot
substring(3) of "Kotlin" lin
substring(2, 5) of "Kotlin" tli
substring(0, 6) of "Kotlin" Kotlin

All lessons in Beginner