Kotlin Strings

A string is a sequence of characters — letters, digits, spaces, and symbols — stored as a single value. In Kotlin, strings are immutable: once created, the text inside cannot change. Any operation that seems to modify a string actually creates a new one.

Creating Strings

val greeting = "Hello, Kotlin!"
val empty = ""
val multiLine = """
    Line one
    Line two
    Line three
""".trimIndent()

Double quotes create a regular string. Triple quotes (""") create a raw string that preserves line breaks and allows any character without escape sequences.

String Templates

Embed variables and expressions directly inside strings using $.

val name = "Siddharth"
val age = 22

println("Name: $name, Age: $age")
// Name: Siddharth, Age: 22

println("In 5 years: ${age + 5}")
// In 5 years: 27

println("Name length: ${name.length}")
// Name length: 9

String Properties and Functions

Length and Access

val word = "Kotlin"

println(word.length)        // 6
println(word[0])            // K  (access by index)
println(word.first())       // K
println(word.last())        // n
println(word.get(3))        // l

Case Conversion

val text = "Hello World"

println(text.uppercase())     // HELLO WORLD
println(text.lowercase())     // hello world
println(text.capitalize())    // Hello World (deprecated in newer Kotlin)

Trimming Whitespace

val padded = "   Kotlin   "
println(padded.trim())        // "Kotlin"
println(padded.trimStart())   // "Kotlin   "
println(padded.trimEnd())     // "   Kotlin"

Checking String Content

val email = "user@estudy247.com"

println(email.contains("@"))             // true
println(email.startsWith("user"))        // true
println(email.endsWith(".com"))          // true
println(email.isEmpty())                 // false
println(email.isNotEmpty())              // true
println("  ".isBlank())                  // true (only spaces)
println("".isEmpty())                    // true

Searching and Replacing

val sentence = "I love Kotlin and Kotlin loves me"

println(sentence.indexOf("Kotlin"))            // 7
println(sentence.lastIndexOf("Kotlin"))        // 19
println(sentence.replace("Kotlin", "Java"))
// I love Java and Java loves me

println(sentence.replaceFirst("Kotlin", "Python"))
// I love Python and Kotlin loves me

Splitting and Joining

// Split a string into a list
val csv = "apple,mango,banana,grape"
val fruits = csv.split(",")
println(fruits)   // [apple, mango, banana, grape]

// Join a list back into a string
val joined = fruits.joinToString(" | ")
println(joined)   // apple | mango | banana | grape

// Join with prefix and suffix
val formatted = fruits.joinToString(", ", "[", "]")
println(formatted)  // [apple, mango, banana, grape]

Diagram — Split and Join

Original:  "apple,mango,banana"
               ↓ split(",")
List:      ["apple", "mango", "banana"]
               ↓ joinToString(" | ")
Result:    "apple | mango | banana"

Substrings

val url = "https://estudy247.com/kotlin"

println(url.substring(8))          // estudy247.com/kotlin
println(url.substring(8, 21))      // estudy247.com
println(url.substringAfter("//"))  // estudy247.com/kotlin
println(url.substringBefore("/kotlin")) // https://estudy247.com
println(url.substringAfterLast("/"))  // kotlin

String Comparison

val a = "Kotlin"
val b = "kotlin"

println(a == b)                          // false — case-sensitive
println(a.equals(b, ignoreCase = true))  // true  — case-ignored
println(a.compareTo(b))                  // negative number (K < k in ASCII)

String Conversion

// String to number
val numStr = "42"
val num = numStr.toInt()
val price = "99.99".toDouble()

// Number to string
val id = 1001
val idStr = id.toString()

// Safe conversion (returns null instead of crashing)
val safe = "abc".toIntOrNull()   // null (not a valid number)
println(safe ?: 0)               // 0

StringBuilder — Building Strings Efficiently

Concatenating strings with + inside a loop creates many temporary strings and wastes memory. Use StringBuilder when you build a string piece by piece in a loop.

val builder = StringBuilder()

for (i in 1..5) {
    builder.append("Item $i")
    if (i < 5) builder.append(", ")
}

println(builder.toString())
// Item 1, Item 2, Item 3, Item 4, Item 5

Diagram — Why StringBuilder Matters

Without StringBuilder (wasteful):
"" + "A" → new String "A"
"A" + "B" → new String "AB"
"AB" + "C" → new String "ABC"
Each step creates a new object in memory.

With StringBuilder:
Buffer: [A][B][C] → one object, append in place
toString() → "ABC"
Only one final String object created.

Leave a Comment

Your email address will not be published. Required fields are marked *