Convert an IntArray to a String in Kotlin
This article explores different ways to convert an IntArray to a String in Kotlin.
1. Using reduce() function
The idea is to map each element of the IntArray to a String and perform a reduction operation on elements using the reduce() function. This can be implemented as follows in Kotlin.
|
1 2 3 4 5 6 |
fun main() { val intArray: IntArray = intArrayOf(1, 2, 3, 4, 5) val str: String = intArray.map { it.toString() }.reduce { x, y -> "$x, $y" } println(str) } |
Output:
1, 2, 3, 4, 5
2. Using contentToString() function
To print the string representation of the contents of an IntArray, use the contentToString() function. The string representation consists of all elements of the array enclosed within [] and the adjacent elements separated by ", ".
|
1 2 3 4 |
fun main() { val intArray: IntArray = intArrayOf(1, 2, 3, 4, 5) println(intArray.contentToString()) } |
Output:
[1, 2, 3, 4, 5]
To remove [ and ] from the string representation, use the replaceAll() function.
|
1 2 3 4 5 |
fun main() { val intArray: IntArray = intArrayOf(1, 2, 3, 4, 5) val str: String = intArray.contentToString().replace("[\\[\\]]".toRegex(), "") println(str) } |
Output:
1, 2, 3, 4, 5
3. Using Loop
The idea here is to create a new string and concatenate each array element to it, separated by ", ".
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
fun getString(intArray: IntArray?): String { if (intArray == null || intArray.isEmpty()) { return "" } var str = intArray[0].toString() for (i in 1 until intArray.size) { str = str + ", " + intArray[i].toString() } return str } fun main() { val intArray: IntArray = intArrayOf(1, 2, 3, 4, 5) val str: String = getString(intArray) println(str) } |
Output:
1, 2, 3, 4, 5
That’s all about converting an IntArray to a String in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)