Substring of a string in Kotlin
To get the substring of a given string in Kotlin, you can use String.substring()
function.
Call substring() function on the given String object, and specify the starting and ending indices of the substring in the string.
str.substring(startIndex, endIndex)
The following is an use case where we extract the substring of a string, given start and end indices.
h e l l o w o r l d <-- str
0 1 2 3 4 5 6 7 8 9 10 <-- indices
start -> 3 9 <- end
|<--------------->|
substring
l o w o r
The function returns the substring defined by the given start and end indices.
The end index is optional. So if you specify only start index, then the substring is extracted from the given start index until the end of the string.
str.substring(startIndex)
The following is an use case where we extract the substring of a string, given start index.
h e l l o w o r l d <-- str
0 1 2 3 4 5 6 7 8 9 10 <-- indices
start -> 3
|<--------------------->|
substring
l o w o r l d
Examples
Get substring from start index to end index
In the following program, we take a string value in str
and get the substring of this string from a start index = 3 to end index = 9.
Kotlin Program
fun main() {
val str = "hello world"
val output = str.substring(3, 9)
println(output)
}
Output
lo wor
Explanation
h e l l o w o r l d <-- str
0 1 2 3 4 5 6 7 8 9 10 <-- indices
start -> 3 9 <- end
|<--------------->|
substring
l o w o r
Get substring from start index
In the following program, we take a string value in str
and get the substring of this string from a start index = 3 to end of the string.
Kotlin Program
fun main() {
val str = "hello world"
val output = str.substring(3)
println(output)
}
Output
lo world
Explanation
h e l l o w o r l d <-- str
0 1 2 3 4 5 6 7 8 9 10 <-- indices
start -> 3
|<--------------------->|
substring
l o w o r l d