kotlinbeginner
String Processing Utilities
Common string operations in Kotlin: split, join, pad, replace, regex, and template processing.
kotlinPress ⌘/Ctrl + Shift + C to copy
fun main() {
// Split and join
val csv = "Alice,30,alice@test.com"
val (name, age, email) = csv.split(",")
println("Name: $name, Age: $age, Email: $email")
val words = "the quick brown fox".split(" ")
println("Capitalized: ${words.joinToString(" ") { it.replaceFirstChar { c -> c.uppercase() } }}")
// Padding
val items = listOf("Laptop" to 999, "Mouse" to 29, "Keyboard" to 79)
println("\n--- Price List ---")
items.forEach { (item, price) ->
println("${item.padEnd(15)} \$${price.toString().padStart(6)}")
}
// Trim variants
val messy = " \t Hello, World! \n "
println("\ntrimmed: '${messy.trim()}'")
println("trimStart: '${messy.trimStart()}'")
println("trimEnd: '${messy.trimEnd()}'")
// Remove prefix/suffix
val filename = "report-2024.csv"
println("\nNo prefix: ${filename.removePrefix("report-")}")
println("No suffix: ${filename.removeSuffix(".csv")}")
println("No surrounding: ${filename.removeSurrounding("report-", ".csv")}")
// Contains, startsWith, endsWith
println("\nContains '2024': ${filename.contains("2024")}")
println("Starts with 'report': ${filename.startsWith("report")}")
println("Ends with '.csv': ${filename.endsWith(".csv")}")
// Replace
val template = "Hello {name}, welcome to {app}!"
val filled = template
.replace("{name}", "Alice")
.replace("{app}", "Kotlin")
println("\n$filled")
// Regex replace
val cleaned = "Price: $99.99 (USD)".replace(Regex("[^\\d.]"), "")
println("Cleaned price: $cleaned")
// Substring
val path = "/api/v2/users/123"
println("\nAfter last '/': ${path.substringAfterLast("/")}")
println("Before last '/': ${path.substringBeforeLast("/")}")
println("After first '/api': ${path.substringAfter("/api")}")
// Char operations
val input = "Hello World 123!"
println("\nDigits only: ${input.filter { it.isDigit() }}")
println("Letters only: ${input.filter { it.isLetter() }}")
println("No spaces: ${input.filterNot { it.isWhitespace() }}")
// Count and checks
println("\nChar count 'l': ${input.count { it == 'l' }}")
println("All letters? ${"".all { it.isLetter() }}")
println("Any digit? ${input.any { it.isDigit() }}")
println("None upper? ${"hello".none { it.isUpperCase() }}")
// StringBuilder
val built = buildString {
append("Line 1")
appendLine()
append("Line 2")
insert(0, "# ")
}
println("\n$built")
// Repeat
println("\n${"-".repeat(30)}")
println("Ha".repeat(5))
// Lines processing
val multiline = """
Line 1
Line 2
Line 3
""".trimIndent()
val numbered = multiline.lines()
.mapIndexed { i, line -> "${i + 1}. $line" }
.joinToString("\n")
println("\n$numbered")
// Conversion
println("\ntoInt: ${"42".toInt()}")
println("toIntOrNull: ${"abc".toIntOrNull()}")
println("toDouble: ${"3.14".toDouble()}")
println("reversed: ${"Kotlin".reversed()}")
println("lowercase: ${"HELLO".lowercase()}")
println("uppercase: ${"hello".uppercase()}")
}Use Cases
- CSV and delimited data parsing
- Template string processing
- Input cleaning and normalization
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
String Templates and Multiline Strings
Format strings in Kotlin: templates, raw strings, trimMargin, trimIndent, and template processing.
Best for: Dynamic string construction and formatting
#kotlin#strings
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
Kotlin String Manipulation Utilities
Essential string operations in Kotlin: templates, multiline, padding, splitting, regex, and buildString.
Best for: Text formatting and report generation
#kotlin#string