Kotlin Tutoial
Basics
Control Flow
Array & String
Functions
Collections
OOPs Concept
Exception Handling
Null Safety
Regex & Ranges
Java Interoperability
Miscellaneous
Android
Strings are one of the most widely used data types in any programming language, and Kotlin provides a rich API for string manipulation. Here's a comprehensive tutorial on strings in Kotlin:
In Kotlin, strings are represented by the String
class.
val name = "Alice" val message = String(charArrayOf('H', 'e', 'l', 'l', 'o'))
Strings are immutable in Kotlin, which means once a string object is created, it cannot be changed.
Kotlin has two types of string literals:
Escaped strings: They may have escaped characters in them.
val s1 = "Hello, World!\n"
Raw strings: They can contain newlines and arbitrary text. They're delimited by triple quotes ("""
).
val s2 = """ This is a string that spans multiple lines in the source code. """
You can use expressions inside string literals using the $
symbol.
val name = "Alice" println("Hello, $name!") // Outputs: Hello, Alice!
For more complex expressions, use ${}
:
val a = 5 println("Square of $a is: ${a * a}") // Outputs: Square of 5 is: 25
Length:
val length = name.length
Concatenation:
val combined = name + " Wonderland"
Substring:
val sub = name.substring(1..3) // Outputs: "lic"
Comparison:
val isEqual = name.equals("ALICE", ignoreCase = true) // true
Conversion:
val upper = name.toUpperCase() val lower = name.toLowerCase()
Splitting:
val words = "Kotlin is fun".split(" ") // [Kotlin, is, fun]
Trimming:
Raw strings often contain additional newlines, you can remove them:
val trimmed = s2.trimMargin()
As we've seen before, you can embed any valid Kotlin expression inside string literals:
val price = 10 println("Price is: $price") // Outputs: Price is: 10 println("Total price: ${price * 2}") // Outputs: Total price: 20
In raw strings, you can also set the margin character and reference it in trimMargin()
. The default character is |
.
val text = """ |Tell me and I forget. |Teach me and I remember. |Involve me and I learn. """.trimMargin()
In escaped strings, special characters can be escaped using a backslash \
.
val sentence = "She said, \"Kotlin is great!\""
You can iterate over a string just like a collection:
for (char in name) { println(char) }
Kotlin offers a robust and concise set of tools for string manipulation, making many tasks easier and more intuitive than in some other languages. By combining string literals, interpolation, and the Kotlin standard library's string extension functions, you can handle most string-related tasks effortlessly.
Creating strings in Kotlin:
val singleLine = "Hello, Kotlin!" val multiLine = """ This is a multiline string in Kotlin. """
String concatenation in Kotlin:
+
operator or the plus
function.val greeting = "Hello" val name = "Kotlin" val message = greeting + ", " + name + "!"
String interpolation in Kotlin:
$
symbol.val age = 25 val info = "I am $age years old."
String templates in Kotlin:
val x = 10 val y = 20 val result = "The sum of $x and $y is ${x + y}."
String methods and functions in Kotlin:
length
, toUpperCase
, toLowerCase
, etc.val text = "Kotlin" val length = text.length val uppercase = text.toUpperCase()
Substring extraction in Kotlin:
substring
function.val original = "Hello, Kotlin!" val substring = original.substring(7, 13)
String length and indices in Kotlin:
val text = "Kotlin" val length = text.length val firstChar = text[0]
String comparison in Kotlin:
==
for content equality or compareTo
for lexicographical ordering.val str1 = "abc" val str2 = "def" val isEqual = str1 == str2
Working with multiline strings in Kotlin:
val multiline = """ Line 1 Line 2 """.trimIndent()
String formatting in Kotlin:
val pi = 3.14159 val formatted = "The value of pi is %.2f".format(pi)
Regex and pattern matching with strings in Kotlin:
val input = "Kotlin123" val regex = "\\d+".toRegex() val hasDigits = regex.containsMatchIn(input)
Null safety and strings in Kotlin:
?.
.val nullableString: String? = null val length = nullableString?.length ?: 0