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.
Syntax
The syntax of the subSequence()
function is as follows:
fun subSequence(
startIndex: Int,
endIndex: Int
): CharSequence
where
Parameter | Description |
---|---|
startIndex | The starting index (inclusive) of the subsequence. |
endIndex | The ending index (exclusive) of the subsequence. |
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.
- Take a string value in
originalString
. - Define the
startIndex
andendIndex
to specify the subsequence range. - Call
subSequence()
function onoriginalString
with the defined indices. The function returns the subsequence. - 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")
}
Output
Original String: Hello, Kotlin!
Subsequence: Kotlin
Summary
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.