Strings in Kotlin
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.
What is a String
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.
Creating Strings
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!"""
Example 1: Initializing Strings
- Create a string variable and initialize it with a value.
- Print the string variable using
println
.
Kotlin Program
fun main() {
val str: String = "Hello, world!"
println(str)
}
Output
Hello, world!
Example 2: Accessing Characters in a String
- Create a string variable and initialize it with a value.
- Access and print individual characters using array indexing or the
get
method.
Kotlin Program
fun main() {
val str: String = "Hello"
println(str[0]) // Accessing using array indexing
println(str.get(1)) // Accessing using get()
}
Output
H e
Example 3: Modifying Strings
- Create a string variable and initialize it with a value.
- Strings in Kotlin are immutable, so create a new string with the modified value.
- Print the modified string.
Kotlin Program
fun main() {
var str: String = "Hello"
str = 'J' + str.substring(1) // Modifying individual character
str += " World!" // Appending new characters
println(str)
}
Output
Jello World!
Example 4: String Concatenation
- Create two string variables and initialize them with values.
- Concatenate the strings using the
+
operator or template strings. - Print the concatenated string.
Kotlin Program
fun main() {
val str1: String = "Hello"
val str2: String = " World!"
val str3: String = str1 + str2 // Concatenating strings
println(str3)
}
Output
Hello World!
Example 5: Finding Substrings
- Create a string variable and initialize it with a value.
- Use the
indexOf
method to find a substring. - Print the position of the found substring.
Kotlin Program
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")
}
}
Output
Found 'world' at position: 7
Example 6: String Length
- Create a string variable and initialize it with a value.
- Use the
length
property to get the length of the string. - Print the length of the string.
Kotlin Program
fun main() {
val str: String = "Hello, world!"
println("Length of the string: " + str.length)
}
Output
Length of the string: 13