Kotlin Strings
In Kotlin, a String is used to store a sequence of characters. Strings are immutable, which means once created, they cannot be changed.
1. Creating Strings
val name = "Kotlin"
val message: String = "Welcome to Kotlin"
2. String Length
val text = "Hello"
println(text.length) // 5
3. Access Characters in a String
val word = "Kotlin"
println(word[0]) // K
println(word[3]) // l
4. String Concatenation
Using + Operator
val first = "Hello"
val second = "Kotlin"println(first + ” “ + second)Using String Templates (Recommended)
val lang = "Kotlin"
println("Welcome to $lang")
5. String Templates with Expressions
val a = 10
val b = 20println(“Sum = ${a + b}“)6. Multi-Line Strings (Triple Quotes)
val text = """
Kotlin is modern
Easy to learn
Powerful language
"""
println(text)
7. Common String Functions
val str = "Kotlin Programming"
println(str.uppercase())
println(str.lowercase())
println(str.length)
println(str.contains(“Kotlin”))
println(str.replace(“Kotlin”, “Java”))
8. Compare Strings
Structural Equality (==)
val a = "Kotlin"
val b = "Kotlin"println(a == b) // trueReferential Equality (===)
println(a === b) // true or false (memory reference)
9. Check Empty or Blank
val s1 = ""
val s2 = " "println(s1.isEmpty()) // trueprintln(s2.isBlank()) // true
10. Escape Characters
println("Hello\nKotlin") // New line
println("Hello\tKotlin") // Tab
println("She said \"Hi\"")
11. Nullable Strings
var name: String? = null
println(name?.length) // Safe call
Summary
-
Strings are immutable
-
Supports string templates
-
Rich built-in functions
-
Supports multi-line strings
Next Topics You Can Learn
-
Kotlin String Functions (Deep)
-
Kotlin Arrays
-
Kotlin Conditions
-
Kotlin Input
