Strings represent sequences of characters and are used to store text in Kotlin programs. Kotlin provides versatile features to work with strings, including templates, interpolation, concatenation, and multiline string support, making text handling both concise and expressive.
Kotlin supports two main ways to declare string literals:
" ") and support escape sequences like \n, \t, etc.
val greeting = "Hello\nKotlin!"
""" """) and can span multiple lines. Escape sequences are interpreted literally.
val multiLine = """This is
a multi-line
string."""
You can combine multiple strings using the + operator:
val firstName = "John"
val lastName = "Doe"
val fullName = firstName + " " + lastName
println(fullName) // Output: John Doe
Kotlin allows embedding variables and expressions directly into strings using templates:
$variableName to insert a variable.
val name = "Alice"
println("Hello, $name!") // Output: Hello, Alice!
${expression} for inline calculations or method calls.
val a = 5
val b = 10
println("Sum of $a and $b is ${a + b}") // Output: Sum of 5 and 10 is 15
You can invoke functions directly within string templates for dynamic output:
fun greet(name: String) = "Hello, $name!"
val message = greet("Kotlin")
println("Message: $message") // Output: Message: Hello, Kotlin!
Kotlin provides multiple built-in methods for manipulating strings:
length — Returns the number of characters.uppercase() / lowercase() — Change text case.trim() — Removes whitespace at the beginning and end.substring(startIndex, endIndex) — Extracts part of a string.replace(oldValue, newValue) — Replaces specific text.val text = " Kotlin is fun! "
println(text.length) // Output: 18
println(text.trim()) // Output: Kotlin is fun!
println(text.uppercase()) // Output: KOTLIN IS FUN!
println(text.substring(2, 8)) // Output: Kotlin
println(text.replace("fun", "awesome")) // Output: Kotlin is awesome!
Raw strings can include leading margins, which can be removed using trimMargin():
val poem = """
|Roses are red,
|Violets are blue,
|Kotlin is fun,
|And so are you.
""".trimMargin()
println(poem)
/* Output:
Roses are red,
Violets are blue,
Kotlin is fun,
And so are you.
*/
trimMargin().fun main() {
val firstName = "Emma"
val lastName = "Stone"
val age = 30
val greeting = "Hello, $firstName $lastName! You are $age years old."
println(greeting)
val poem = """
|Roses are red,
|Violets are blue,
|Kotlin is fun,
|And so are you.
""".trimMargin()
println(poem)
}
Output:
Hello, Emma Stone! You are 30 years old.
Roses are red,
Violets are blue,
Kotlin is fun,
And so are you.