Menu
Coddy logo textTech

Building Text Efficiently

Part of the Logic & Flow section of Coddy's Kotlin journey. Lesson 47 of 63.

StringBuilder accumulates text with append calls, then toString produces the final String. You can append labels, numbers and separators inside a loop without manually rebuilding a whole immutable String on every step. Decide exactly where separators belong.

Inside main:

val result = StringBuilder()
for (n in 1..3) {
    if (n > 1) result.append("-")
    result.append(n)
}
println(result.toString())

The separator is added before each item except the first, avoiding a trailing hyphen.

Use StringBuilder.append for incremental text and toString for the final String.

challenge icon

Challenge

Medium

Complete numberLine with parameters count: Int. Use StringBuilder to return the numbers from 1 through count separated by a single hyphen, with no leading or trailing hyphen. count is between 0 and 20; zero returns an empty string.

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 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 numberLine(count: Int): String {
    // Write your solution here.
    return ""
}
fun main() {
    val count = readln().toInt()
    println(numberLine(count))
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow

Practice on your own: Kotlin playground