Splitting and Joining
Part of the Logic & Flow section of Coddy's Kotlin journey. Lesson 46 of 63.
trim removes leading and trailing whitespace. split separates text into pieces using a delimiter, and joinToString combines pieces using a chosen separator. These operations let you normalize simple delimited input. Here the delimiter is literal text, not a regular expression.
Inside main:
val parts = " red, blue ,green ".trim().split(",").map { it.trim() }
println(parts.joinToString(" | "))The comma splits the fields, trim cleans each field, and the final separator is inserted between fields.
Trim individual fields after splitting when surrounding field spaces should be removed.
Challenge
MediumComplete cleanFields with parameters text: String. Split text on literal commas, trim each field, and discard empty fields. Return the remaining fields in input order.
Unless stricter bounds are stated above, collections contain at most 100 elements at each level, and integer arguments and integer collection values are between -1000 and 1000. Text supplied for parsing can include invalid or out-of-range representations as described.
Return a value of type List<String>. Keep the supplied input/output code. It reads scalar arguments one per line; a list starts with its count followed by its elements, and a map starts with its entry count followed by each key and value. Nested lists repeat the count-and-elements format for each row. The supplied main prints the return value followed by one newline. Lists use Kotlin's standard bracketed format; print no additional labels.
Try it yourself
fun cleanFields(text: String): List<String> {
// Write your solution here.
return emptyList()
}
fun main() {
val text = readLine().orEmpty()
println(cleanFields(text))
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
4Nested Collections
Lists of ListsTraversing RowsRow SummariesFlattening Nested ListsRecap - Seating Rows7Collection Pipelines
Transforming with MapFiltering ValuesTesting Collection RulesAccumulating with FoldRecap - Approved Totals10Text Processing
Splitting and JoiningBuilding Text EfficientlyMatching Text PatternsFinding and ReplacingRecap - Code Cleaner5Project - Contact Book
Save ContactsFind ContactsPractice on your own: Kotlin playground