Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Kotlin: How to create a string by repeating a character a given number of times

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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")
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading