
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Print All Elements of a String Array in Kotlin
In this article, we will take an example and show how to print all the elements of a String array in a single line using a Kotlin library class. In order to do that, we will use a String function called joinToString(), provided by the Kotlin library.
As per the Kotlin documentation, the function definition looks like this −
fun <T> Array<out T>.joinToString( // the String will be separated by this separator: CharSequence = ", ", // This will be added as prefix to the String prefix: CharSequence = "", // This will be added as postfix to the String postfix: CharSequence = "", // This number of element will be printed, // the remaining elements will be denoted but truncated sequence limit: Int = -1, truncated: CharSequence = "...", //any transformation required over the String transform: ((T) -> CharSequence)? = null ): String
This function takes several attributes in order to convert an arrayList into a String.
Example - Printing all elements of a String array in a single line
fun main(args: Array<String>) { val mylist = listOf("Jam", "bread", "apple", "mango") println( mylist.joinToString( prefix = "[", separator = "-", postfix = "]", truncated = "...", ) ) }
Output
On execution, it will produce the following output −
[Jam-bread-apple-mango]
Advertisements