Kotlin strings play a critical role in almost every Kotlin program. They are sequences of characters used for storing text such as user inputs, messages, and processing data. In Kotlin, a string is represented by the String class. Understanding how Kotlin strings work and how to manipulate them effectively is essential for any Kotlin developer.
In Kotlin, the String class represents immutable strings. This immutability means that once a string is created, it cannot be changed. Attempting to modify the string’s value will result in creating a new string object. The strings in Kotlin are UTF-16 encoded sequences of characters, which means they generally use approximately 2 bytes per character.
A typical String value in Kotlin is enclosed in double quotes:
1val str = "abcd 123"
Kotlin String elements can be accessed through indexing operations, like s[i], where 'i' represents a valid character index within the string. The range of valid character indices for this char sequence can be easily determined. Kotlin provides the ability to loop over these characters easily:
1for (c in str) { 2 println(c) 3}
When dealing with concatenation, Kotlin recommends using string templates over the traditional + operator, which is still available if the first element in the concatenation is string kotlin.
Kotlin offers two types of string literals: escaped strings and multi-line strings.
A string literal in Kotlin is defined with double quotes, making it easy to create a String value:
1val helloWorld = "Hello, World!"
Escaped strings are capable of containing escape characters such as newlines and tabs, improving readability in complex String values. In Kotlin, an escaped string is declared within double quotes and may contain escape characters like \n
, \t
, \b
, etc. For instance, consider a string with a newline:
1val escapedString = "Hello, world!\n"
Kotlin uses backslashes \
as escape characters, which is a common practice in many programming languages. These sequences allow inserting special characters into String values that would otherwise be difficult to express. Kotlin supports various escaped characters, including \n
for a new line, \t
for a tab, and \\
for a backslash itself.
Kotlin’s escaped strings are conventional and easy to understand, they maintain compatibility with Java String values, making it easier for developers transitioning to or from Java.
When dealing with String values that span multiple lines, Kotlin offers a convenient feature called multi-line strings. These literals are enclosed by triple quotes """, form a raw string, and do not require additional escape sequences:
1val multiLineString = """ 2 The quick brown fox 3 jumps over the lazy dog. 4"""
Multi-line strings accept arbitrary text and preserve line breaks, providing a clean solution for embedding formatted text, code snippets, or any character sequence within a string.
To handle leading whitespace in multi-line strings, String offers the trimMargin() method. By default, the pipe | serves as a margin prefix, but you can specify a different character if needed:
1val textWithMargin = """ 2 |Tell me and I forget. 3 |Teach me and I remember. 4 |Involve me and I learn. 5 |(Benjamin Franklin) 6 """.trimMargin()
Kotlin’s string templates enhance the dynamism of strings by allowing variables and expressions to be embedded within them. Starting with a dollar sign ($), followed by either a variable name or curly braces enclosing an expression, string templates make it easy to construct strings with embedded values or execute arbitrary expressions:
1val name = "Jane" 2println("Hello, $name!") // Output: Hello, Jane! 3 4val score = 12 5println("Your score is ${score * 2}") // Output: Your score is 24
String templates are a powerful feature, especially when combined with escaped or multi-line strings, streamlining the code and enhancing readability.
Kotlin provides a variety of operations that you can perform on strings. For instance, string comparison can be achieved using (structural equality) or = (referential equality), depending on whether you want to compare the string content or the reference to the String object. When comparing an object with another for order, it returns zero if they are equal, a negative number if the first object is less than the specified object, or a positive number if it's greater than the specified object.
You can access string elements by their indexes, which start from zero. You can also request a substring, get the string length, or find the first occurrence of a character:
1val example = "Kotlin" 2println(example[0]) // Output: K 3println(example.length) // Output: 6 4println(example.substring(1..3)) // Output: otl
Building upon the basic operations, Kotlin strings also encompass a set of advanced methods for more complex text manipulations. Let’s explore some of these methods by starting with how we can modify the case of a string:
1val kotlinString = "Kotlin is Awesome!" 2println(kotlinString.lowercase()) // Output: kotlin is awesome! 3println(kotlinString.uppercase()) // Output: KOTLIN IS AWESOME!
In Kotlin, a 'char sequence' is used in various string operations and utility functions, such as checking if the sequence is empty, retrieving characters at specific indices, iterating over characters, transforming the sequence, and working with regular expressions.
Kotlin strings can also be used to check for the presence or match of a substring or pattern using regular expressions:
1val searchString = "Kotlin" 2val matchResult = kotlinString.contains(searchString) 3println(matchResult) // Output: true 4 5val regex = Regex("[A-Z]") 6println(kotlinString.contains(regex)) // Output: true
Each of these methods returns a new string, which is a fundamental characteristic of strings being immutable. Modifying characters, trimming whitespace, or even replacing sequences within the string results in a brand-new String object, preserving the original one.
String templates in Kotlin not only make strings more intuitive but also significantly cleaner when injecting variables or expressions. The power of string templates is aptly demonstrated when you are combining multiple string elements. Consider the situation where you want to include a dynamic value within a string:
1val itemCount = 5 2val pricePerItem = 9.99 3println("Total cost: $${itemCount * pricePerItem}") // Total cost: $49.95
Notice here how we use the $ symbol to denote the start of a template expression. When needing to escape the dollar character itself, Kotlin developers can use the ${'$'} syntax.
Moving on to multi-line strings, templates can greatly improve the readability and maintainability:
1val multiLineWithTemplate = """ 2 |Kotlin version: ${KotlinVersion.CURRENT} 3 |Kotlin is fun: $true 4 """.trimMargin() 5println(multiLineWithTemplate)
Here, the trimMargin() function ensures that the leading whitespace is removed, while keeping the indentation of the block intact, which makes the code a lot more readable.
String templates highlight their strength when used inside loop constructs. Imagine you have an array of main args and you wish to print them with some extra information:
1fun main(args: Array<String>) { 2 for (arg in args) { 3 println("Argument received: $arg") 4 } 5}
In this fun main loop, for each element in the main args array string, the $arg template expression injects the value directly into the print statement.
The String class in Kotlin is quite versatile. Let’s look at the instantiation and some common methods associated with the class:
1val stringInstance = String() // Creates an empty string 2val charArray = charArrayOf('K', 'o', 't', 'l', 'i', 'n') 3val stringFromChars = String(charArray) 4println(stringFromChars) // Output: Kotlin
To return a new character sequence from a character sequence, you can use the substring method, specifying the start and end indices.
Strings in Kotlin are pooled. This implies that if two strings are equal (content-wise), they might reference the same string object in memory, which is an optimization technique known as string interning.
While strings are a fundamental part of programming, handling them efficiently demands awareness of best practices:
• Prefer string templates or raw strings over the + operator for concatenation.
• Converting an object to its string representation is crucial for debugging and logging purposes.
• Use StringBuilder for complex or numerous modifications to avoid creating many temporary string objects.
• Be mindful of the immutability of strings; operations on strings return new instances.
To master Kotlin strings, it's crucial to understand their properties and how to effectively utilize them. Remember that strings are immutable and the String class is feature-packed to handle almost every use case you can encounter. Let this be a stepping stone to digging deeper into Kotlin string methods and harnessing their full potential.
To further explore Kotlin strings and their methods, consider the following resources:
• Kotlin Documentation
• Various online Kotlin playgrounds
• Community forums and Kotlin development discussions
The below section will cover some of the most common questions developers have regarding strings in Kotlin, from immutable properties to template usage.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.