Skip to main content
Kotlin Basics
CHAPTER 11 Beginner

Strings in Kotlin

Updated: May 18, 2026
5 min read

# CHAPTER 11

Strings in Kotlin

1. Chapter Introduction

Strings represent sequences of characters (text). Whether you are displaying an article to a user, parsing JSON from a server, or validating a password input, you are working with Strings. Kotlin provides a rich set of built-in methods to manipulate, format, and search text. In this chapter, we will explore advanced String templates, essential String operations, and Raw Strings (Triple-quoted strings).

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Access individual characters in a String.
  • Use built-in String methods (length, uppercase, substring).
  • Compare strings securely.
  • Create multi-line "Raw Strings" using triple quotes.

3. Strings are Immutable

Just like in Java, Strings in Kotlin are Immutable. Once a String object is created in memory, its contents can never be changed. Operations that appear to modify a String (like .uppercase()) actually create and return a *brand new String object*.

4. Basic String Operations

You can treat a String almost like an Array of characters.
kotlin
123456789101112131415
fun main() {
    val message = "Kotlin"

    // Getting the length (Number of characters)
    println("Length: ${message.length}") // 6

    // Accessing individual characters by index
    println("First letter: ${message[0]}") // K
    println("Last letter: ${message[5]}")  // n
    
    // Iterating over a string
    for (char in message) {
        print("$char ") // K o t l i n 
    }
}

5. Essential String Methods

Kotlin provides dozens of helper methods to process text.
kotlin
1234567891011121314151617181920212223
fun main() {
    val text = "  Learn Kotlin Today  "

    // Removing whitespace from the beginning and end
    val cleanText = text.trim() 
    println("Trimmed: '$cleanText'") // 'Learn Kotlin Today'

    // Case conversion
    println(cleanText.uppercase()) // LEARN KOTLIN TODAY
    println(cleanText.lowercase()) // learn kotlin today

    // Searching inside a string
    println(cleanText.contains("Kotlin")) // true
    println(cleanText.startsWith("Learn")) // true

    // Replacing text
    val newText = cleanText.replace("Today", "Tomorrow")
    println(newText) // Learn Kotlin Tomorrow

    // Substrings (Extracting a portion)
    val word = cleanText.substring(6, 12) // Extracts from index 6 up to 11
    println("Extracted: $word") // Kotlin
}

6. String Comparison

To check if two strings contain the exact same text, use ==. To ignore uppercase/lowercase differences, use .equals(..., ignoreCase = true).
kotlin
123456789
fun main() {
    val pass1 = "Secret123"
    val pass2 = "secret123"

    println(pass1 == pass2) // false (case sensitive)
    
    // Ignore case
    println(pass1.equals(pass2, ignoreCase = true)) // true
}

7. Raw Strings (Triple Quotes)

If you need to print a massive block of text, formatting it with \n (newlines) and \" (escaped quotes) is a nightmare. Kotlin introduces Raw Strings using three double quotes """. Raw strings can span multiple lines and do not require escaping characters!
kotlin
12345678910
fun main() {
    // A multiline raw string
    val sqlQuery = """
        SELECT * FROM users
        WHERE age > 18
        AND status = 'ACTIVE'
    """.trimIndent() // Removes the leading indentation for a clean print!

    println(sqlQuery)
}

8. Common Mistakes

  • IndexOutOfBounds: Remember that Strings are 0-indexed. If a string has a length of 5, the maximum index is 4. Trying to access str[5] will crash the program.
  • Forgetting Reassignment: Because Strings are immutable, writing text.trim() does nothing to the original variable. You must assign the result to a new variable: val cleaned = text.trim().

9. Best Practices

  • Use .trimIndent(): Whenever you use a multiline Raw String ("""), append .trimIndent(). This allows you to indent the string in your code to make it look pretty, without actually printing those huge blocks of blank space to the console.

10. Exercises

  1. 1. Create a variable password = " P@ssw0rd ".
  1. 2. Create a new variable cleanPass by trimming the whitespace.
  1. 3. Check if cleanPass contains the @ symbol and print the boolean result.
  1. 4. Print the cleanPass in all uppercase.

11. MCQs with Answers

Question 1

Are Strings mutable or immutable in Kotlin?

Question 2

How do you get the number of characters in a String?

Question 3

How do you access the first letter of a String variable named text?

Question 4

Which method removes leading and trailing whitespace from a String?

Question 5

How do you check if two strings contain the exact same characters?

Question 6

If you want to compare two strings but ignore capital letters, what should you use?

Question 7

What syntax is used to create a multi-line "Raw String"?

Question 8

What does .trimIndent() do to a Raw String?

Question 9

If val s = "Kotlin", what does s.substring(0, 3) return?

Q10. Do String Templates ($) work inside Raw Strings (""")? a) Yes b) No Answer: a) Yes.

12. Interview Questions

  • Q: What does it mean that Strings are "Immutable"? Why is this good for memory? (Answer: Once created, they cannot be changed. This allows the JVM to safely reuse string instances in a "String Pool" without worrying that one part of the app will secretly alter the string for another part).
  • Q: Explain how Kotlin handles String equality (==) compared to Java.

13. Summary

Strings in Kotlin are robust and feature-rich. By leveraging methods like .trim(), .replace(), and .substring(), text processing becomes trivial. The addition of Triple-quoted Raw Strings makes embedding HTML, JSON, or SQL queries directly into Kotlin code incredibly clean and readable.

14. Next Chapter Recommendation

We have hinted at Null Safety several times. It is time to face it head-on. In Chapter 12: Null Safety in Kotlin, we will explore Kotlin's defining feature: the eradication of the Null Pointer Exception.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·