String Length and Substring in Kotlin
Introduction
String Length and Substring is a fundamental concept every Kotlin developer should understand. Strings appear in almost every program — user input, file paths, API responses, and UI labels. Kotlin’s standard library provides concise helpers for common text tasks.
The length property returns the number of characters in a string. In this tutorial you will learn the syntax, walk through a complete example program, study the sample output, and review best practices so you can apply the concept confidently in your own projects.
Definition
- The length property returns the number of characters in a string.
- substring(start) and substring(start, end) extract part of a string.
- String indices start from zero like arrays.
Syntax
val len = text.length
val part = text.substring(0, 4)String Length and Substring in Kotlin Example Program in Kotlin
fun main(args: Array<String>) {
val text = "Little Drops"
println("Length: ${text.length}")
println("Substring: ${text.substring(0, 6)}")
}Sample Output
Length: 12
Substring: LittleWhen to use
Use string functions when formatting output, validating user input, splitting CSV data, or building URLs and file paths.
How it works
-
The program starts with a
mainfunction — the entry point that runs when you execute the file. -
val text = "Little Drops"assigns or updates a value used later in the program. -
The
println("Length: ${text.length}")statement writes a line to the console — this produces part of the sample output below. -
The
println("Substring: ${text.substring(0, 6)}")statement writes a line to the console — this produces part of the sample output below. -
The length property returns the number of characters in a string.
-
Run the program in IntelliJ IDEA, Android Studio, or with the Kotlin command-line compiler (
kotlinc/kotlin). Compare your console output with the sample output shown below.
Best Practices
Common Mistakes
Key Points
- The length property returns the number of characters in a string.
- substring(start) and substring(start, end) extract part of a string.
- String indices start from zero like arrays.
- Test the example locally and verify the output matches the sample.
- Experiment by changing input values to see how behaviour changes.
Notes
- Semicolons at the end of statements are optional in Kotlin.