Introduction
Strings in Kotlin are objects that represent sequences of characters. They are immutable, meaning that once a string is created, its value cannot be changed. Kotlin provides a rich set of methods and properties to manipulate strings effectively. This chapter will cover the basics of creating strings, common string operations, string templates, and string interpolation in Kotlin.
Creating Strings
In Kotlin, strings can be created using string literals, which are enclosed in double quotes.
Example
fun main() {
val greeting = "Hello, Kotlin!"
println(greeting)
}
Explanation:
val greeting = "Hello, Kotlin!": Declares a string variable namedgreetingand initializes it with the value "Hello, Kotlin!".println(greeting): Prints the value of thegreetingvariable.
Output:
Hello, Kotlin!
Common String Operations
1. String Length
You can get the length of a string using the length property.
Example
fun main() {
val text = "Kotlin"
println("Length: ${text.length}")
}
Explanation:
text.length: Returns the number of characters in thetextstring.
Output:
Length: 6
2. Accessing Characters
You can access individual characters in a string using the index operator [].
Example
fun main() {
val text = "Kotlin"
println("First character: ${text[0]}")
println("Last character: ${text[text.length - 1]}")
}
Explanation:
text[0]: Returns the first character of thetextstring.text[text.length - 1]: Returns the last character of thetextstring.
Output:
First character: K
Last character: n
3. Substring
You can extract a substring from a string using the substring function.
Example
fun main() {
val text = "Hello, Kotlin!"
val substring = text.substring(7, 13)
println("Substring: $substring")
}
Explanation:
text.substring(7, 13): Extracts a substring from thetextstring starting at index 7 and ending at index 12 (excluding 13).
Output:
Substring: Kotlin
4. String Concatenation
You can concatenate strings using the + operator or string templates.
Example
fun main() {
val firstName = "John"
val lastName = "Doe"
val fullName = firstName + " " + lastName
println("Full name: $fullName")
}
Explanation:
firstName + " " + lastName: Concatenates thefirstNameandlastNamestrings with a space in between.
Output:
Full name: John Doe
String Templates
String templates allow you to embed expressions inside string literals. The expressions are evaluated and their results are concatenated into the string.
Example
fun main() {
val name = "Alice"
val age = 25
val message = "My name is $name and I am $age years old."
println(message)
}
Explanation:
$name: Embeds the value of thenamevariable into the string.$age: Embeds the value of theagevariable into the string.
Output:
My name is Alice and I am 25 years old.
Complex Expressions
For complex expressions, you can use curly braces {} inside string templates.
Example
fun main() {
val a = 5
val b = 10
val sum = "The sum of $a and $b is ${a + b}."
println(sum)
}
Explanation:
${a + b}: Evaluates the expressiona + band embeds the result into the string.
Output:
The sum of 5 and 10 is 15.
String Functions
Kotlin provides a variety of built-in functions to manipulate strings.
1. toUpperCase and toLowerCase
Converts all characters in a string to uppercase or lowercase.
Example
fun main() {
val text = "Kotlin"
println("Uppercase: ${text.toUpperCase()}")
println("Lowercase: ${text.toLowerCase()}")
}
Explanation:
text.toUpperCase(): Converts all characters intextto uppercase.text.toLowerCase(): Converts all characters intextto lowercase.
Output:
Uppercase: KOTLIN
Lowercase: kotlin
2. trim
Removes leading and trailing whitespace from a string.
Example
fun main() {
val text = " Kotlin "
println("Trimmed: '${text.trim()}'")
}
Explanation:
text.trim(): Removes leading and trailing whitespace fromtext.
Output:
Trimmed: 'Kotlin'
3. replace
Replaces occurrences of a substring within a string with another substring.
Example
fun main() {
val text = "Hello, Kotlin!"
val newText = text.replace("Kotlin", "World")
println(newText)
}
Explanation:
text.replace("Kotlin", "World"): Replaces "Kotlin" with "World" in thetextstring.
Output:
Hello, World!
4. split
Splits a string into a list of substrings based on a delimiter.
Example
fun main() {
val text = "one,two,three"
val parts = text.split(",")
println(parts)
}
Explanation:
text.split(","): Splits thetextstring into a list of substrings using the comma,as the delimiter.
Output:
[one, two, three]
5. joinToString
Joins elements of a collection into a single string with a specified delimiter.
Example
fun main() {
val parts = listOf("one", "two", "three")
val text = parts.joinToString(", ")
println(text)
}
Explanation:
parts.joinToString(", "): Joins the elements of thepartslist into a single string, separated by,.
Output:
one, two, three
Example Program with Strings
Here is an example program that demonstrates the use of various string operations and functions in Kotlin:
fun main() {
// Creating strings
val greeting = "Hello, Kotlin!"
println(greeting)
// String length
val text = "Kotlin"
println("Length: ${text.length}")
// Accessing characters
println("First character: ${text[0]}")
println("Last character: ${text[text.length - 1]}")
// Substring
val substring = greeting.substring(7, 13)
println("Substring: $substring")
// String concatenation
val firstName = "John"
val lastName = "Doe"
val fullName = firstName + " " + lastName
println("Full name: $fullName")
// String templates
val name = "Alice"
val age = 25
val message = "My name is $name and I am $age years old."
println(message)
// Complex expressions in string templates
val a = 5
val b = 10
val sum = "The sum of $a and $b is ${a + b}."
println(sum)
// String functions
println("Uppercase: ${text.toUpperCase()}")
println("Lowercase: ${text.toLowerCase()}")
println("Trimmed: '${text.trim()}'")
val newText = greeting.replace("Kotlin", "World")
println(newText)
// Splitting and joining strings
val splitText = "one,two,three"
val parts = splitText.split(",")
println(parts)
val joinedText = parts.joinToString(", ")
println(joinedText)
}
Output:
Hello, Kotlin!
Length: 6
First character: K
Last character: n
Substring: Kotlin
Full name: John Doe
My name is Alice and I am 25 years old.
The sum of 5 and 10 is 15.
Uppercase: KOTLIN
Lowercase: kotlin
Trimmed: 'Kotlin'
Hello, World!
[one, two, three]
one, two, three
Conclusion
In this chapter, you learned about strings in Kotlin, including their syntax and usage for creating strings, performing common string operations, using string templates, and utilizing built-in string functions. Understanding how to work with strings is essential for manipulating and formatting text in your Kotlin programs.