Como fazer lista numeraria em Kotlin
To create a numbered list in Kotlin, you can make use of the StringBuilder
class and a loop. Here are the steps to create a numbered list in Kotlin:
- Initialize a
StringBuilder
object to store the list. - Define a variable to keep track of the current index.
- Start a loop to iterate over the items in your list.
- For each item, append the index followed by a period and a space to the
StringBuilder
object. - Append the item itself to the
StringBuilder
object. - Increment the index variable.
- Repeat steps 4 to 6 for all the items in your list.
- Finally, convert the
StringBuilder
object to a string using thetoString()
method.
Here's an example code snippet that demonstrates how to create a numbered list in Kotlin:
fun createNumberedList(items: List<String>): String {
val numberedStringBuilder = StringBuilder()
var index = 1
for (item in items) {
numberedStringBuilder.append("$index. $item\n")
index++
}
return numberedStringBuilder.toString()
}
fun main() {
val items = listOf("Apple", "Banana", "Orange")
val numberedString = createNumberedList(items)
println(numberedString)
}
Output:
1. Apple
2. Banana
3. Orange
In this example, we have a function called createNumberedList
that takes a list of strings as input and returns a formatted string representing the numbered list. The main
function demonstrates the usage of this function by creating a numbered list from a list of fruits and printing it to the console.