kotlinbeginner
Kotlin String Manipulation Utilities
Essential string operations in Kotlin: templates, multiline, padding, splitting, regex, and buildString.
kotlinPress ⌘/Ctrl + Shift + C to copy
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.
kotlinbeginner
Extension Functions and Properties
Add methods to existing classes without inheritance: extension functions, properties, and generic extensions.
Best for: Adding utility methods to third-party types
#kotlin#extensions
kotlinbeginner
File I/O — Read, Write, and Process
Read and write files in Kotlin: readText, useLines, buffered I/O, and file tree walking.
Best for: Configuration file reading and writing
#kotlin#file-io
kotlinbeginner
String Processing Utilities
Common string operations in Kotlin: split, join, pad, replace, regex, and template processing.
Best for: CSV and delimited data parsing
#kotlin#strings
kotlinbeginner
Null Safety — Elvis, Safe Call, and let
Master Kotlin null safety: safe calls, Elvis operator, let/also scoping, and smart casts.
Best for: Safe navigation through nullable chains
#kotlin#null-safety