0
0
KotlinHow-ToBeginner · 3 min read

How to Use Substring in Kotlin: Syntax and Examples

In Kotlin, you can use the substring function to extract a part of a string by specifying start and optional end indices. For example, str.substring(2, 5) returns characters from index 2 up to but not including index 5.
📐

Syntax

The substring function extracts a part of a string using indices.

  • substring(startIndex: Int): Returns substring from startIndex to the end.
  • substring(startIndex: Int, endIndex: Int): Returns substring from startIndex up to but not including endIndex.

Indices start at 0, meaning the first character is at index 0.

kotlin
val text = "Hello, Kotlin!"
val part1 = text.substring(7)       // from index 7 to end
val part2 = text.substring(0, 5)    // from index 0 to 4
println(part1)
println(part2)
Output
Kotlin! Hello
💻

Example

This example shows how to get a substring from a string using both forms of substring. It extracts the word "Kotlin" and the greeting "Hello" from the original string.

kotlin
fun main() {
    val greeting = "Hello, Kotlin!"
    val fromIndex = 7
    val toIndex = 13

    val sub1 = greeting.substring(fromIndex, toIndex)  // "Kotlin"
    val sub2 = greeting.substring(0, 5)                // "Hello"

    println(sub1)
    println(sub2)
}
Output
Kotlin Hello
⚠️

Common Pitfalls

Common mistakes when using substring include:

  • Using indices out of the string's range causes StringIndexOutOfBoundsException.
  • Confusing endIndex as inclusive, but it is exclusive.
  • Negative indices are not allowed.

Always check string length before calling substring.

kotlin
fun main() {
    val text = "Kotlin"
    // Wrong: endIndex is inclusive here, will cause error
    // val wrong = text.substring(2, 10) // Error: StringIndexOutOfBoundsException

    // Right: endIndex must be <= text.length
    val right = text.substring(2, 5) // "tli"
    println(right)
}
Output
tli
📊

Quick Reference

Remember these tips when using substring in Kotlin:

  • Indices start at 0.
  • startIndex is inclusive, endIndex is exclusive.
  • substring(startIndex) extracts till the end.
  • Check string length to avoid errors.

Key Takeaways

Use substring(startIndex, endIndex) to get part of a string from startIndex up to but not including endIndex.
Indices start at 0 and endIndex is exclusive, so be careful with boundaries.
Calling substring with out-of-range indices causes errors, always check string length first.
substring(startIndex) extracts from startIndex to the string's end.
Remember negative indices are not allowed in substring calls.