kotlinbeginner

Kotlin String Manipulation Utilities

Essential string operations in Kotlin: templates, multiline, padding, splitting, regex, and buildString.

kotlin
fun main() {
    // String templates
    val name = "Alice"
    val age = 30
    println("Name: $name, Age: $age")
    println("Next year: ${age + 1}")

    // Multiline / raw strings
    val json = """
        {
            "name": "$name",
            "age": $age
        }
    """.trimIndent()
    println(json)

    // trimMargin with custom prefix
    val sql = """
        |SELECT *
        |FROM users
        |WHERE age > $age
        |ORDER BY name
    """.trimMargin()
    println(sql)

    // Padding and alignment
    println("hello".padStart(10))          // "     hello"
    println("hello".padEnd(10, '-'))        // "hello-----"
    println("42".padStart(5, '0'))          // "00042"

    // Substring operations
    val path = "/users/alice/profile.jpg"
    println(path.substringAfterLast('/'))    // profile.jpg
    println(path.substringBeforeLast('/'))   // /users/alice
    println(path.removeSuffix(".jpg"))       // /users/alice/profile
    println(path.removePrefix("/"))          // users/alice/profile.jpg

    // Split and join
    val csv = "apple, banana, cherry"
    val fruits = csv.split(",").map { it.trim() }
    println("Fruits: $fruits")
    println("Joined: ${fruits.joinToString(" | ")}")

    // Case conversion
    println("hello world".replaceFirstChar { it.uppercase() })

    // Checks
    println("  ".isBlank())        // true
    println("".isEmpty())           // true
    println("abc123".all { it.isLetterOrDigit() }) // true

    // buildString
    val table = buildString {
        appendLine("| Name    | Score |")
        appendLine("|---------|-------|")
        listOf("Alice" to 95, "Bob" to 87).forEach { (n, s) ->
            appendLine("| ${n.padEnd(7)} | ${s.toString().padStart(5)} |")
        }
    }
    println(table)

    // Repeat
    println("=".repeat(40))
    println("Ha".repeat(3))
}

Use Cases

  • Text formatting and report generation
  • Path and URL manipulation
  • Data masking and sanitization

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.