Home > Software design >  Kotlin: How to create a string by repeating a character a given number of times
Kotlin: How to create a string by repeating a character a given number of times

Time:01-27

I am trying to print a line below a title. The idea is that the line is the same length as the title. I have tried several ways and I think this is the closest, but the result it gives me is not correct.

fun main() {

    val chapters = arrayOf("Basic syntax", "Idioms", "Kotlin by example", "Coding conventions")

    for (numCharpter in chapters.indices){
        // Print the name of the chapter
        val title = "Charpter ${numCharpter   1}: ${chapters[numCharpter]}"
        val arrayDash = Array(title.length) {'='}
        val stringDash = arrayDash.toString()


        println("$title\n$stringDash\n")

        // the rest of the code
    }
}

the output i want is:

Charpter 1: Basic syntax
========================

Charpter 2: Idioms
==================

Charpter 3: Kotlin by example
=============================

Charpter 4: Coding conventions
==============================

the output i get is:

Charpter 1: Basic syntax
[Ljava.lang.Character;@24d46ca6
Charpter 2: Idioms
[Ljava.lang.Character;@4517d9a3
Charpter 3: Kotlin by example
[Ljava.lang.Character;@372f7a8d
Charpter 4: Coding conventions
[Ljava.lang.Character;@2f92e0f4

Is there a simple way to initialize a String by repeating a character?

CodePudding user response:

val chapters = arrayOf("Basic syntax", "Idioms", "Kotlin by example", "Coding conventions")

for (numCharpter in chapters.indices) {
  val title = "Chapter ${numCharpter   1}: ${chapters[numCharpter]}"
  val line = "=".repeat(title.length)
  println("$title\n$line\n")
}

CodePudding user response:

val chapters = arrayOf("Basic syntax", "Idioms", "Kotlin by example", "Coding conventions")

val titles = chapters.mapIndexed { index, chapter ->
  "Chapter ${index   1}: $chapter".let { it   "\n"   "=".repeat(it.length)   "\n" }
}

for (title in titles) {
  println(title)
}

Or more readable:

val chapters = arrayOf("Basic syntax", "Idioms", "Kotlin by example", "Coding conventions")

val titles = chapters
  .mapIndexed { index, chapter ->
    "Chapter ${index   1}: $chapter"
      .let { title ->
        buildString {
          append(title)
          append("\n")
          append("=".repeat(title.length))
          append("\n")
        }
      }
  }

for (title in titles) {
  println(title)
}

CodePudding user response:

A further simplified variation of the solution of @lukas.j might look like this:

val chapters = arrayOf("Basic syntax", "Idioms", "Kotlin by example", "Coding conventions")
val titles = chapters
    .mapIndexed { index, chapter ->
        buildString {
            append("Chapter ${index   1}: $chapter")
            append('\n')
            repeat(length - 1) { append('=') }
            append("\n")
        }
    }
      
titles.forEach { println(it) }      
  •  Tags:  
  • Related