Strings in Kotlin
📌 Strings in Kotlin
In Kotlin, a String is a sequence of characters enclosed within double quotes (" "). Strings are immutable, meaning their contents cannot be changed once created. Kotlin provides various functions and operations to manipulate and handle strings efficiently.
✅ Creating Strings
📌 1. String Declaration
val greeting: String = "Hello, Kotlin!"println(greeting) // Output: Hello, Kotlin!
📌 2. Multiline String (Raw String)
Use triple quotes """ """ to declare a multiline string.
val multilineText = val name = "Vikash"val age = 30println("My name is $name and I am years old.")
Output:
My nameis Vikash and I am 30 years old.
For expressions, use
${}:
val a = 5val b = 10println("The sum of $a and is ${a + b}")
Output:
The sum of 5and10is15
✅ String Comparison in Kotlin
📌 1. Using == for Structural Comparison
Compares the content of two strings.
val str1 = "Kotlin"val str2 = "Kotlin"println(str1 == str2) // Output: true
📌 2. Using === for Referential Comparison
Compares memory addresses (checks if both refer to the same object).
val str3 = "Kotlin"val str4 = str3println(str3 === str4) // Output: true
✅ String Iteration
You can iterate over the characters of a string using a for loop:
val str = "Hello"for (char in str) { println(char)}
Output:
Hello
✅ Convert String to Other Types
You can easily convert a string to other data types using functions like:
| Conversion | Function | Example | Output |
|---|---|---|---|
| String to Int | toInt() | "123".toInt() | 123 |
| String to Double | toDouble() | "123.45".toDouble() | 123.45 |
| String to Boolean | toBoolean() | "true".toBoolean() | true |
| Int to String | toString() | 123.toString() | "123" |
✅ Conclusion
Strings are immutable in Kotlin.
Use string interpolation for cleaner code.
Perform string operations using various built-in functions.
Compare strings using
==and===.Convert between data types easily using type conversion functions.