我正试图在标题下打印一条线。意思是这一行和标题的长度是一样的。我尝试了几种方法,我认为这是最接近的,但它给我的结果是不正确的。
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
}
}我想要的输出是:
Charpter 1: Basic syntax
========================
Charpter 2: Idioms
==================
Charpter 3: Kotlin by example
=============================
Charpter 4: Coding conventions
==============================我得到的输出是:
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是否有一种简单的方法通过重复一个字符来初始化一个字符串?
发布于 2022-01-26 16:17:43
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")
}发布于 2022-01-26 17:00:00
@lukas.j解决方案的进一步简化可能如下所示:
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) } 发布于 2022-01-26 16:30:48
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)
}或更易读:
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)
}https://stackoverflow.com/questions/70866577
复制相似问题