Kotlin Example To Convert Array to String

Last updated Apr 21, 2021

In this example we will cover how to convert char array to String in Kotlin. In this kotlin example we will take the array elements from command line by scanner class and make array and finally convert array to string. If you are beginner to kotlin read Kotlin String

 

Example

package com.rrtutors.lib


import java.util.*

//Main Function entry Point of Program
fun main(args: Array) {
    //Input Stream
    val scanner = Scanner(System.`in`)

    //Input Char Array Size
    print("Enter Array size: ")
    val size = scanner.nextInt()

    //Create Character array of Given size
    val charArray = CharArray(size)

    //Input array elements
    println("Enter Array Elements:")
    for (i in charArray.indices) {
        print("charArray[$i] : ")
        charArray[i] = scanner.next()[0]
    }

    //Print All Array Elements
    println("Array : ${charArray.contentToString()} ")

    //Get String from Cahr Array
    var strFromArray = String(charArray)

    //print String from Array
    println("String to Array in Kotlin  : $strFromArray")
}

 

Code Explanation:

Step 1: First will take the size of array from user by command line input and assign to size variable

Step 2: Create an array with the size given by user as CharArray(size)

Step 3: Now Take array inputs from user from commandline by using scanner class

Step 4: Now finally we will convert char array to String by String() property.

 

Output:

Enter Char Array size: 5
Enter Char Arrays Elements:
charArray[0] : a
charArray[1] : b
charArray[2] : c
charArray[3] : d
charArray[4] : e
Array : [a, b, c, d, e]
String to Array in Kotlin  : abcde

 

Conclusion: In this kotlin example we learn how to convert array to string and also learn take inputs from commandline arguments by using scanner class.

 

Related: Kotlin convert String to Array

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

1036 Views