String.substring() / drop() / take()
In Kotlin, you can extract a substring by position using substring(), or by character count from the start or end using drop() and take().
Syntax
// By position val sub: String = string.substring(startIndex) val sub2: String = string.substring(startIndex, endIndex) // endIndex is exclusive // By character count from start or end val d: String = string.drop(n) // Returns the string with the first n characters removed val t: String = string.take(n) // Returns the first n characters val dl: String = string.dropLast(n) // Returns the string with the last n characters removed val tl: String = string.takeLast(n) // Returns the last n characters
Method List
| Method | Description |
|---|---|
| string.substring(start) | Returns the substring from start to the end. |
| string.substring(start, end) | Returns the substring from start up to (but not including) end. |
| string.drop(n) | Returns the string with the first n characters removed. |
| string.take(n) | Returns the first n characters. |
| string.dropLast(n) | Returns the string with the last n characters removed. |
| string.takeLast(n) | Returns the last n characters. |
| string.dropWhile { } | Removes characters from the start while the condition is true. |
| string.takeWhile { } | Takes characters from the start while the condition is true. |
Sample Code
fun main() {
val s = "Hello, Kotlin!"
// Extract a substring by specifying positions.
println(s.substring(7)) // Kotlin!
println(s.substring(7, 13)) // Kotlin (index 13 is not included)
// Specify character counts with drop / take.
println(s.take(5)) // Hello
println(s.drop(7)) // Kotlin!
println(s.takeLast(7)) // Kotlin!
println(s.dropLast(7)) // Hello,
// Specify a condition with dropWhile / takeWhile
val csv = "000123"
println(csv.dropWhile { it == '0' }) // 123 (leading zeros removed)
println(csv.takeWhile { it == '0' }) // 000 (only leading zeros)
// You can also get a substring using the range operator.
println(s[0..4]) // Hello (indices 0 to 4)
}
Notes
Indices in substring() are zero-based, and the character at the end index is not included. Specifying an out-of-range index throws a StringIndexOutOfBoundsException.
drop() and take() are safe to use — they do not throw an exception when n is greater than the string length.
For checking string length, see string.length / isEmpty(). For splitting and joining, see string.split() / joinToString().
If you find any errors or copyright issues, please contact us.