Home > front end >  How to split an array in java or Kotlin?
How to split an array in java or Kotlin?

Time:05-18

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

CodePudding user response:

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.

CodePudding user response:

I assume a generic array with elements that does have a proper implementation of Object::equals; for a mere array of char, the suggested solutions based on the String operations are the most effective implementations.

Try this:

final Element [] input = …
final List<Element[]> output = new ArrayList<>();
final Element split = …

var start = 0;
var end = 0;
while( end < input.length )
{
  if( input [end].equals( split )
  {
    output.add( Arrays.copyOfRange( input( start, end ) );
    start = end   1;
  }
    end;
}
if( start < end ) output.add( Arrays.copyOfRange( input( start, end ) );

CodePudding user response:

Why not just

val arr = arrayOf('H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd')
val arr1 = arr.take(5).toTypedArray()// or .joinToString()
val arr2 = arr.takeLast(5).toTypedArray()// or .joinToString()

5 is hardcoded but another way is to work with the space index

CodePudding user response:

Converting the array to a String and splitting it in Java:

    final String[] array = { "H", "e", "l", "l", "o", " ", "W", "o", "r", "l", "d" };
    final String[] arr = String.join("", array).split(" ");
    final String[] subArray1 = arr[0].split("");
    final String[] subArray2 = arr[1].split("");

CodePudding user response:

Did it in Java for fun. Not very concise though. I cant seem to be able to do it using Streams properly.

public static void main(String[] args) {
        char[] chars = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'};
        char[][] char2d;

        String[] tokens = String.valueOf(chars).split(" ");
        char2d = new char[tokens.length][];
        for (int i=0; i< tokens.length; i  ) {
            char2d[i] = tokens[i].toCharArray();
        }

        for (int i=0; i< char2d.length; i  ){
            System.out.println(Arrays.toString(char2d[i]));
        }
    }

Output:

[H, e, l, l, o]
[W, o, r, l, d]

Managed to replicate it with streams as follows:

char[][] char2d2 = Arrays.stream(tokens).map(String::toCharArray).toArray(char[][]::new);
for (int i=0; i< char2d2.length; i  ){
    System.out.println(Arrays.toString(char2d2[i]));
}

Gives the same output as above.

  • Related