DEV Community

myougaTheAxo
myougaTheAxo

Posted on

Kotlin String Operations — Templates, Regex & Multiline Strings

Kotlin String Operations

Master Kotlin's powerful string handling with templates, raw strings, extension functions, and regex.

String Templates

The simplest syntax for embedding values:

val name = "みょうが"
val age = 3

// Simple variable
println("Name: $name")  // Name: みょうが

// Expression
println("Age next year: ${age + 1}")  // Age next year: 4

// Nested templates
val items = listOf("feed", "bubbles")
println("Favorites: ${items.joinToString(", ")}")  // Favorites: feed, bubbles

// Raw template (print $variable literally)
println("\$name = $name")  // $name = みょうが
Enter fullscreen mode Exit fullscreen mode

Multiline Strings

Triple quotes with smart trimming:

val poem = """
    |みょうがはピンク
    |かわいい
    |エサがすき
""".trimMargin()  // Removes leading | and indentation

val message = """
    Dear user,

    This is indented.
""".trimIndent()  // Removes common leading whitespace
Enter fullscreen mode Exit fullscreen mode

Extension Functions

Kotlin's stdlib provides powerful string utilities:

val input = "  hello world  "

// Null/blank checks
input.isNotBlank()  // true
"".isNullOrBlank()  // true

// Split & Join
"a,b,c".split(",")  // [a, b, c]
listOf("x", "y").joinToString("-")  // x-y

// Substring operations
"hello".take(2)  // he
"hello".takeLast(2)  // lo
"hello".drop(1)  // ello
"hello".substringBefore('l')  // he
"hello".substringAfter('l')  // lo

// Padding
"5".padStart(3, '0')  // 005
"hi".padEnd(5, '*')  // hi***

// Case conversion
"Hello".uppercase()  // HELLO
"Hello".lowercase()  // hello
"hello-world".replaceFirstChar { it.uppercase() }  // Hello-world

// Contains checks
"kotlin".contains("lin")  // true
"kotlin".startsWith("kot")  // true
"kotlin".endsWith("in")  // true
Enter fullscreen mode Exit fullscreen mode

Regular Expressions

Pattern matching and replacement:

val text = "Email: user@example.com"

// Test match
if (text.matches(Regex(".*@.*\.com"))) {
    println("Valid email format")
}

// Find first match
val email = text.find(Regex("\w+@\w+\.\w+"))
println(email?.value)  // user@example.com

// Replace
text.replace(Regex("\w+"), "*")  // Email: ****@*******.**

// Find all matches
val numbers = "1a2b3c".findAll(Regex("\d"))
numbers.forEach { println(it.value) }  // 1, 2, 3

// Destructured groups
val pattern = Regex("(\w+)@(\w+)\.(\w+)")
val (username, domain, ext) = pattern.find(text)?.destructured!!
println("$username at $domain")  // user at example
Enter fullscreen mode Exit fullscreen mode

Formatting

Numeric and datetime formatting:

// Number formatting
String.format("%d", 42)  // 42
String.format("%05d", 7)  // 00007
String.format("%.2f", 3.14159)  // 3.14

// Using format extension
"Total: %,d items".format(1000)  // Total: 1,000 items

// DateTime (Java interop)
val formatter = java.time.format.DateTimeFormatter
    .ofPattern("yyyy-MM-dd HH:mm")
val now = java.time.LocalDateTime.now()
println(formatter.format(now))  // 2026-03-02 12:00
Enter fullscreen mode Exit fullscreen mode

Build String (DSL)

Efficient string concatenation:

val report = buildString {
    append("Summary:
")
    append("- Items: 5
")
    append("- Status: Active
")

    // With expressions
    if (isPremium) {
        append("- Tier: Premium
")
    }
}
Enter fullscreen mode Exit fullscreen mode

Android Resources with Plurals

Handle singular/plural in Android strings.xml:

<!-- res/values/strings.xml -->
<plurals name="items">
    <item quantity="one">%d item</item>
    <item quantity="other">%d items</item>
</plurals>
Enter fullscreen mode Exit fullscreen mode
val count = 1
val text = resources.getQuantityString(R.plurals.items, count, count)
println(text)  // 1 item

val count2 = 5
val text2 = resources.getQuantityString(R.plurals.items, count2, count2)
println(text2)  // 5 items
Enter fullscreen mode Exit fullscreen mode

String Resources with Substitution

<!-- res/values/strings.xml -->
<string name="greeting">Hello, %1$s! You have %2$d messages.</string>
Enter fullscreen mode Exit fullscreen mode
val message = getString(R.string.greeting, "みょうが", 3)
println(message)  // Hello, みょうが! You have 3 messages.
Enter fullscreen mode Exit fullscreen mode

Ready to build Android apps faster? Download our 8 Android app templates.

Top comments (0)