In this tutorial, you shall learn how to get the substring of given string in Kotlin, which is defined by starting and ending index, using String.subSequence() function, with examples.

Kotlin – Get Substring of a String

To get substring of a String in Kotlin, use String.subSequence() method.

Given a string str1, and if we would like to get the substring from index startIndex until the index endIndex, call subSequence() method on string str1 and pass the indices startIndex and endIndex respectively as arguments to the method as shown below.

str1.subSequence(startIndex, endIndex)

subSequence() method returns the substring of this string.

Examples

ADVERTISEMENT

1. Get substring in given string

In this example, we will take a string in str1, and get the substring from this string that starts at index 2 and ends at index 7.

Kotlin Program

fun main(args: Array<String>) {
    val str1 = "abcdefghij"
    val startIndex = 2
    val endIndex = 7
    val substring = str1.subSequence(startIndex, endIndex)
    println("The substring is : " + substring)
}

Output

The substring is : cdefg

Explanation

string    a b c d e f g h i j
index     0 1 2 3 4 5 6 7 8 9
startIndex    *
endIndex                *
substring     ---------
              c d e f g

2. Index out of bounds for string

If the any of the start index or end index is out of bounds for the given string, the subSequence() method throws java.lang.StringIndexOutOfBoundsException.

Kotlin Program

fun main(args: Array<String>) {
    val str1 = "abcdefghij"
    val startIndex = -2
    val endIndex = 7
    val substring = str1.subSequence(startIndex, endIndex)
    println("The substring is : " + substring)
}

Output

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin -2, end 7, length 10
	at java.base/java.lang.String.checkBoundsBeginEnd(String.java:3107)
	at java.base/java.lang.String.substring(String.java:1873)
	at java.base/java.lang.String.subSequence(String.java:1912)
	at KotlinExampleKt.main(KotlinExample.kt:5)

Conclusion

In this Kotlin Tutorial, we learned how to get the substring of a given string using String.subSequence() method, with the help of Kotlin example programs.