0

I have tried str.split(,).toTypedArray(), but it doesn’t make an array.

var tasks = ""

tasks.plus(",").plus("Hey")
tasks.plus(",").plus("Hey")
tasks.plus(",").plus("Hey")
tasks.plus(",").plus("Hey")

val array = tasks.split(",").toTypedArray()

array.forEach {println(it)}

the output returns nothing so far.

Is there a way to split the string where the input is:

"xyx yxy xyx" and get an output: ["xyx","yxy","xyx"]

1
  • Yes Commented Jul 31, 2019 at 18:43

3 Answers 3

1

In Kotlin strings are immutable, so don't expect this:

tasks.plus(",").plus("Hey")

to append anything to tasks.
The operator function plus() returns the string that you want to append but does not also append it.
You must do it like this:

tasks = tasks.plus(",").plus("Hey")
tasks = tasks.plus(",").plus("Hey")
tasks = tasks.plus(",").plus("Hey")
tasks = tasks.plus(",").plus("Hey")

and then with:

val array = tasks.split(",").toTypedArray()
array.forEach { println(it) }

the result that will be printed is:

<empty line here because of the 1st comma>
Hey
Hey
Hey
Hey
Sign up to request clarification or add additional context in comments.

3 Comments

Though if you're going to construct a string, calling plus() is a very inefficient way of doing it. (It will create ever-longer temporary copies.) Far better to append everything to a StringBuilder, and then convert that to a String at the end.
@gidds I aggree with you. My answer is not about the efficiency of the method but why it does not work as the OP says.
Oh, I wasn't criticising your answer, which is good! I was just adding a further point about the code (as it's something people tend to get wrong).
0

You can split the string based on the space char using split which returns a List then call toTypedArray to produce an array from that list.

val arr = "xyx yxy xyx".split(" ").toTypedArray();

Here's an online Demo.

Comments

0

tasks in your code remains empty, the following works as expected:

var tasks = ""

tasks = tasks.plus(",").plus("Hey")
.plus(",").plus("Hey")
.plus(",").plus("Hey")
.plus(",").plus("Hey")

val array = tasks.split(",").toTypedArray()

You can actually have have tasks as val like so:

val tasks = ",".plus("Hey")
.plus(",").plus("Hey")
.plus(",").plus("Hey")
.plus(",").plus("Hey")

or even

val tasks = ",Hey,Hey,Hey,Hey"

and also

",Hey,Hey,Hey,Hey".split(",").forEach { println(it) }

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.