Kotlin Example to convert String to Array

Published April 21, 2021


In this Kotlin programming example we will convert a given string to array by using Strings toCharArray() method. In this example we will read string from user input by scanner class.

 

Example:

package com.rrtutors.lib


import java.util.*

//Main Function entry Point of Program
fun main(args: Array<String>) {
    // InputStream to get Input
    val scanner = Scanner(System.`in`)

    //Input String
    print("Enter a String : ")
    var str = scanner.nextLine()

    //convert String to Character Array
    val charArray = str.toCharArray()

    //Print Character Array get from String
    println("Converted String to Char Array  : ${charArray.contentToString()} ")
}

 

Code Explanation:

Step 1: Create a String by taking user inputs from command line argument using Scanner class

Step 2: Convert given string to array by using str.toCharArray() method

 

Output:

Enter a String : Convert to String to Char Array
Converted String to Char Array  : [C, o, n, v, e, r, t,  , t, o,  , S, t, r, i, n, g,  , t, o,  , C, h, a, r,  , A, r, r, a, y]

 

Conclusion: In this kotlin example we learn how to convert string to array using toCharArray() method.

 

Related: Kotlin convert Array to string

 


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

253 Views

Subscribe For Daily Updates

Flutter Questions
Android Questions