9

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.

1
  • 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 stackoverflow.com/questions/40878804/…, and use builtin IntelliJ J2K converter. Commented Sep 26, 2019 at 15:36

5 Answers 5

13

Something like this:

val str = "abcd"
val array: Array<String> = str.toCharArray().map { it.toString() }.toTypedArray()
Sign up to request clarification or add additional context in comments.

2 Comments

A bit simpler: str.map { it.toString() }.toTypedArray()
You can also simply allocate the result to a string list like this:val listStr: List<String> = str.map { it.toString() }
8

Try This:

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

fun main() {
    println(arr) // [, H, e, l, l, o]
}

2 Comments

String.split("") returns a List<String>, but the question is about Array<String>.
You can append .toTypedArray() to convert list to array
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) }
}

Comments

1

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

Comments

1
fun main() {
    val string = "Hello"
    val array = Array(string.length) { string[it].toString() }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.