Kotlin Strings — Declaration, Access, and Common Operations
A String in Kotlin is an immutable sequence of characters. This tutorial covers everything from declaration to common string functions.
What You Will Learn
- Declare and access Kotlin strings
- Get length and individual characters
- Concatenate strings
- Common string functions: uppercase, lowercase, trim, replace
- Check if a string is empty or blank
Declaring Strings
Basic String Declaration
fun main() {
val language = "Kotlin"
val greeting = "Hello, World!"
println(language)
println(greeting)
println(language.length)
}.length gives the number of characters in the string. "Kotlin" has 6 characters.
Accessing Characters
Character Access
fun main() {
val word = "Kotlin"
println(word[0]) // first character
println(word[5]) // last character
println(word.first())
println(word.last())
}word[0] accesses the character at index 0. .first() and .last() are convenience functions for the first and last characters.
Common String Functions
Common String Operations
fun main() {
val text = " Hello, Kotlin! "
println(text.trim()) // remove whitespace
println(text.trim().uppercase())
println(text.trim().lowercase())
println(text.trim().replace("Kotlin", "World"))
println(text.trim().contains("Hello"))
println(text.trim().startsWith("Hello"))
println(text.trim().endsWith("!"))
}.trim() removes leading and trailing whitespace. .uppercase() / .lowercase() change case. .replace() substitutes substrings. .contains(), .startsWith(), .endsWith() return booleans.
Checking Empty and Blank Strings
isEmpty vs isBlank
fun main() {
val empty = ""
val blank = " "
val filled = "Kotlin"
println(empty.isEmpty()) // true
println(blank.isEmpty()) // false
println(blank.isBlank()) // true
println(filled.isBlank()) // false
}isEmpty() returns true only for a string with zero characters. isBlank() returns true for an empty string or one containing only whitespace.
String Concatenation
Concatenation vs Templates
fun main() {
val first = "Kotlin"
val second = "Guide"
// Concatenation with +
println(first + second)
// String template (preferred)
println("$first$second")
println("Welcome to $first$second.com")
}+ concatenates strings. String templates are more readable and preferred in Kotlin style.
Practice Exercise
What does this print? val s = " Kotlin " println(s.trim().length)
Quick Quiz
What is the difference between isEmpty() and isBlank()?
Frequently Asked Questions
Related Tutorials
Written by KotlinGuide Editorial Team · Reviewed by KotlinGuide Technical Review