Introduction
Kotlin provides a rich set of built-in functions to manipulate strings effectively. These functions allow you to perform common tasks such as searching, replacing, formatting, and splitting strings. This chapter will cover the most commonly used string functions in Kotlin with examples.
1. length
The length
property returns the number of characters in a string.
Example
fun main() {
val text = "Kotlin"
println("Length: ${text.length}")
}
Output:
Length: 6
2. get and []
The get
function and the []
operator are used to access characters at specific positions in a string.
Example
fun main() {
val text = "Kotlin"
println("First character: ${text[0]}")
println("Last character: ${text[text.length - 1]}")
}
Output:
First character: K
Last character: n
3. substring
The substring
function extracts a substring from a string, given a range of indices.
Example
fun main() {
val text = "Hello, Kotlin!"
val substring = text.substring(7, 13)
println("Substring: $substring")
}
Output:
Substring: Kotlin
4. toUpperCase and toLowerCase
These functions convert all characters in a string to uppercase or lowercase, respectively.
Example
fun main() {
val text = "Kotlin"
println("Uppercase: ${text.toUpperCase()}")
println("Lowercase: ${text.toLowerCase()}")
}
Output:
Uppercase: KOTLIN
Lowercase: kotlin
5. trim, trimStart, and trimEnd
The trim
function removes leading and trailing whitespace from a string. trimStart
and trimEnd
remove leading and trailing whitespace, respectively.
Example
fun main() {
val text = " Kotlin "
println("Trimmed: '${text.trim()}'")
println("Trimmed start: '${text.trimStart()}'")
println("Trimmed end: '${text.trimEnd()}'")
}
Output:
Trimmed: 'Kotlin'
Trimmed start: 'Kotlin '
Trimmed end: ' Kotlin'
6. replace
The replace
function 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)
}
Output:
Hello, World!
7. split
The split
function 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)
}
Output:
[one, two, three]
8. joinToString
The joinToString
function 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)
}
Output:
one, two, three
9. contains
The contains
function checks if a string contains a specified substring.
Example
fun main() {
val text = "Hello, Kotlin!"
println("Contains 'Kotlin': ${text.contains("Kotlin")}")
println("Contains 'Java': ${text.contains("Java")}")
}
Output:
Contains 'Kotlin': true
Contains 'Java': false
10. startsWith and endsWith
The startsWith
and endsWith
functions check if a string starts or ends with a specified substring.
Example
fun main() {
val text = "Hello, Kotlin!"
println("Starts with 'Hello': ${text.startsWith("Hello")}")
println("Ends with 'Kotlin!': ${text.endsWith("Kotlin!")}")
}
Output:
Starts with 'Hello': true
Ends with 'Kotlin!': true
11. indexOf and lastIndexOf
The indexOf
function returns the index of the first occurrence of a substring, and lastIndexOf
returns the index of the last occurrence.
Example
fun main() {
val text = "Hello, Kotlin! Kotlin is fun."
println("First occurrence of 'Kotlin': ${text.indexOf("Kotlin")}")
println("Last occurrence of 'Kotlin': ${text.lastIndexOf("Kotlin")}")
}
Output:
First occurrence of 'Kotlin': 7
Last occurrence of 'Kotlin': 15
12. isEmpty and isBlank
The isEmpty
function checks if a string is empty, and isBlank
checks if a string is empty or contains only whitespace.
Example
fun main() {
val emptyText = ""
val blankText = " "
println("Is empty: ${emptyText.isEmpty()}")
println("Is blank: ${blankText.isBlank()}")
}
Output:
Is empty: true
Is blank: true
Example Program with String Functions
Here is an example program that demonstrates the use of various string functions in Kotlin:
fun main() {
val text = " Hello, Kotlin! Kotlin is fun. "
// Length of the string
println("Length: ${text.length}")
// Accessing characters
println("First character: ${text[0]}")
println("Last character: ${text[text.length - 1]}")
// Substring
val substring = text.substring(7, 13)
println("Substring: $substring")
// Uppercase and lowercase
println("Uppercase: ${text.toUpperCase()}")
println("Lowercase: ${text.toLowerCase()}")
// Trim, trimStart, and trimEnd
println("Trimmed: '${text.trim()}'")
println("Trimmed start: '${text.trimStart()}'")
println("Trimmed end: '${text.trimEnd()}'")
// Replace
val newText = text.replace("Kotlin", "World")
println("Replaced: $newText")
// Split
val parts = text.split(" ")
println("Split: $parts")
// Join
val joinedText = parts.joinToString(", ")
println("Joined: $joinedText")
// Contains
println("Contains 'Kotlin': ${text.contains("Kotlin")}")
println("Contains 'Java': ${text.contains("Java")}")
// Starts with and ends with
println("Starts with 'Hello': ${text.startsWith("Hello")}")
println("Ends with 'fun.': ${text.endsWith("fun.")}")
// Index of and last index of
println("First occurrence of 'Kotlin': ${text.indexOf("Kotlin")}")
println("Last occurrence of 'Kotlin': ${text.lastIndexOf("Kotlin")}")
// Is empty and is blank
val emptyText = ""
val blankText = " "
println("Is empty: ${emptyText.isEmpty()}")
println("Is blank: ${blankText.isBlank()}")
}
Output:
Length: 30
First character:
Last character:
Substring: Kotlin
Uppercase: HELLO, KOTLIN! KOTLIN IS FUN.
Lowercase: hello, kotlin! kotlin is fun.
Trimmed: 'Hello, Kotlin! Kotlin is fun.'
Trimmed start: 'Hello, Kotlin! Kotlin is fun. '
Trimmed end: ' Hello, Kotlin! Kotlin is fun.'
Replaced: Hello, World! World is fun.
Split: [ , , Hello,, Kotlin!, Kotlin, is, fun., , ]
Joined: , , Hello,, Kotlin!, Kotlin, is, fun., ,
Contains 'Kotlin': true
Contains 'Java': false
Starts with 'Hello': false
Ends with 'fun.': false
First occurrence of 'Kotlin': 8
Last occurrence of 'Kotlin': 15
Is empty: true
Is blank: true
Conclusion
In this chapter, you learned about various string functions in Kotlin, including their syntax and usage for performing common string operations such as searching, replacing, formatting, and splitting strings. Understanding how to use these functions is essential for effective string manipulation in your Kotlin programs.