Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert String to String array in Kotlin?

I want to know how I can convert one string or a String Object in a String array using kotlin.

I made some research and found this JAVA code which seems to do what I need.

public static void main(String[] args) { 
String word="abc";
        String[] array = new String[word.length()];
        for(int i = 0; i < word.length(); i++)
        {
            array[i] = String.valueOf(word.charAt(i));
        }

        for(String a:array){
            System.out.println(a);
        }
}

I expect to have something like this or better than it in Kotlin.

Thanks in advance.

like image 420
Félix Maroy Avatar asked Dec 06 '22 09:12

Félix Maroy


2 Answers

Something like this:

val str = "abcd"
val array: Array<String> = str.toCharArray().map { it.toString() }.toTypedArray()
like image 97
Artem Botnev Avatar answered Dec 07 '22 22:12

Artem Botnev


Try This:

val str = "Hello"
val arr = str.split("")

fun main() {
    println(arr) // [, H, e, l, l, o]
}
like image 44
francis Avatar answered Dec 07 '22 21:12

francis