In this tutorial, we will learn about strings in Kotlin. We will cover the basics of string manipulation, including creating, accessing, modifying, and performing operations on strings.
A string in Kotlin is a sequence of characters. Strings in Kotlin are immutable, meaning their values cannot be changed once created. Strings are used for storing and handling text data.
Strings can be created in Kotlin using double quotes:
val str: String = "Hello, world!"
Strings can also be created using triple quotes for raw string literals:
val str2: String = """Hello, world!"""
println
.fun main() {
val str: String = "Hello, world!"
println(str)
}
Hello, world!
get
method.fun main() {
val str: String = "Hello"
println(str[0]) // Accessing using array indexing
println(str.get(1)) // Accessing using get()
}
H e
fun main() {
var str: String = "Hello"
str = 'J' + str.substring(1) // Modifying individual character
str += " World!" // Appending new characters
println(str)
}
Jello World!
+
operator or template strings.fun main() {
val str1: String = "Hello"
val str2: String = " World!"
val str3: String = str1 + str2 // Concatenating strings
println(str3)
}
Hello World!
indexOf
method to find a substring.fun main() {
val str: String = "Hello, world!"
val pos: Int = str.indexOf("world") // Finding substring
if (pos != -1) {
println("Found 'world' at position: $pos")
} else {
println("Substring not found")
}
}
Found 'world' at position: 7
length
property to get the length of the string.fun main() {
val str: String = "Hello, world!"
println("Length of the string: " + str.length)
}
Length of the string: 13