</>
Skip to content
Kotlin lessons (10/33)

Kotlin — Strings

String basics

fun main() {
    val s = "Hello, World!"
    val raw = """Raw string
with newlines"""

    println(s.length)        // 13
    println(s[0])            // H
    println(s.substring(0, 5)) // Hello
    println(s.uppercase())   // HELLO, WORLD!
}

String templates

fun main() {
    val name = "Alice"
    val age = 30

    println("Name: $name")
    println("Age: ${age + 1}")
    println("Uppercase: ${name.uppercase()}")
    println("Length: ${name.length}")
}

String operations

fun main() {
    val s = "Hello, World!"

    println(s.contains("World"))    // true
    println(s.startsWith("Hello"))  // true
    println(s.endsWith("!"))        // true
    println(s.indexOf("World"))     // 7
    println(s.replace("World", "Kotlin")) // Hello, Kotlin!
    println(s.split(", "))          // [Hello, World!]
    println(s.trim())               // Hello, World!
}

StringBuilder

val sb = StringBuilder()
sb.append("Hello")
sb.append(" ")
sb.append("World")
val result = sb.toString()
println(result) // Hello World

Regex

fun main() {
    val regex = "\\d+".toRegex()
    val matches = regex.findAll("abc123def456")
    matches.forEach { println(it.value) } // 123 456

    println(regex.containsMatchIn("abc123")) // true
    println(regex.replace("abc123def456", "#")) // abc#def#
}

Mini Practice

Write Kotlin code that:

  1. Uses string templates with expressions
  2. Splits a CSV string and prints each field
  3. Uses regex to find all numbers in a string
  4. Builds a string with StringBuilder

Up Next

In the next lesson, you'll learn about If Else — conditional branching in Kotlin.

Related Topics

Frequently Asked Questions about Strings

What is Strings in Kotlin?

Strings is a fundamental concept in Kotlin. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Strings?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Strings.

Why is Strings important in Kotlin?

Strings is essential for Kotlin development. Understanding this concept will help you write better code and solve real-world problems more effectively.