8

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.

Félix Maroy
  • 1,389
  • 2
  • 16
  • 21
  • Well, it's complicated. Java sample is incorrect, thus, direct translations to Kotlin are incorrect, too. The problem is that `char` is not a character or code point but a UTF-16 word which can represent a half of a code point. See https://stackoverflow.com/questions/40878804/how-to-count-grapheme-clusters-or-perceived-emoji-characters-in-java, and use builtin IntelliJ J2K converter. – Miha_x64 Sep 26 '19 at 15:36

5 Answers5

12

Something like this:

val str = "abcd"
val array: Array<String> = str.toCharArray().map { it.toString() }.toTypedArray()
Artem Botnev
  • 2,267
  • 1
  • 14
  • 19
8

Try This:

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

fun main() {
    println(arr) // [, H, e, l, l, o]
}
francis
  • 3,852
  • 1
  • 28
  • 30
5

You can fill an array as you initialize it using a lambda that takes the index as an argument.

fun main() {
    val word = "abcd"
    val array = Array(word.length) {word[it].toString()}
    array.forEach { println(it) }
}
Tenfour04
  • 83,111
  • 11
  • 94
  • 154
1

You can use java.text.BreakIterator both from Java and Kotlin-JVM to iterate through 'grapheme clusters', i. e. user-visible 'characters'.

Miha_x64
  • 5,973
  • 1
  • 41
  • 63
1
fun main() {
    val string = "Hello"
    val array = Array(string.length) { string[it].toString() }
}