Issue
How can we split an array? For example, I have an array of chars like this:
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
Now, I want to split the array with the spaces which can be seen on the position 6. After splitting the array will look like this:
Array1 = ['H', 'e', 'l', 'l', 'o']
Array2 = ['W', 'o', 'r', 'l', 'd']
I did find a post something like this over here but that is not in java or Kotlin.
I know I could have done it this way:
String str = TextUtils.join(",", arr);
String[] splittedString = str.split(" ");
but, I want another way if it is possible. This takes up a lot of memory and also takes about 30-40 milliseconds on large arrays
How can I do this with java or Kotlin
Solution
A simple solution is joining the original array into a string, split by space and then split again into the characters (here in kotlin):
arr.joinToString().split(" ").map{ it.split() }
This is not optimized but still in O(n)
(linear complexity). It benefits from readability which most often should be preferred whereas performance should be addressed if this is critical to your task at hand.
Answered By - Stuck
Answer Checked By - Pedro (JavaFixing Volunteer)