Kotlin String.subSequence()

Kotlin String.subSequence() Tutorial

The String.subSequence() function in Kotlin is used to get a subsequence of the original string from a specific start index unto a specific end index.

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


The syntax of the subSequence() function is as follows:

fun subSequence(
    startIndex: Int,
    endIndex: Int
): CharSequence


startIndexThe starting index (inclusive) of the subsequence.
endIndexThe ending index (exclusive) of the subsequence.
Parameters of String.subSequence() function

The startIndex is the index of the first character to include in the subsequence, and the endIndex is the index of the first character to exclude from the subsequence. The function returns a CharSequence that represents the specified subsequence.

Examples for String subSequence() function

1. Extracting Subsequence

In this example, we’ll use subSequence() to extract a subsequence from a given string.

  1. Take a string value in originalString.
  2. Define the startIndex and endIndex to specify the subsequence range.
  3. Call subSequence() function on originalString with the defined indices. The function returns the subsequence.
  4. You may print the returned subsequence to the console output.

Kotlin Program

fun main() {
    val originalString = "Hello, Kotlin!"

    // Using subSequence() to extract a subsequence
    val subsequence = originalString.subSequence(7, 13)

    // Printing the original string and the result
    println("Original String: $originalString")
    println("Subsequence: $subsequence")


Original String: Hello, Kotlin!
Subsequence: Kotlin


In this tutorial, we’ve covered the subSequence() function in Kotlin strings, its syntax, and how to use it to extract a specified subsequence. This function provides a flexible way to obtain parts of a string based on the specified indices.