Markovian8261
Markovian8261

Reputation: 899

splitting a string array in java

What would be the best way to split a string array in certain index to make a string matrix removing the element you split. For example, for the string array ["Good","Bad","Sad"] if i split it at 1 it would give me a string matrix that looked like this [["Good"],["Sad"]]

Upvotes: 0

Views: 194

Answers (2)

Kent
Kent

Reputation: 195039

well ivanovic's answer explains how to simply remove one element from a string sequence with java Collection (List). And it is indeed the straightforward way to achieve that goal (removing element).

However, my understanding of OP's question is, he gets an string array as parameter, and wants a 2-D String array to get returned. the "split-index" element should not be included in the result String[][].

Base on my understanding, I therefore add another answer:

final String[] input = new String[] { "one", "two", "three", "four", "five", "six", "seven", "eight" };
        final int len = input.length;
        final int pos = 3;
        final String[][] result = new String[2][Math.max(pos, len - pos - 1)];
        result[0] = Arrays.copyOf(input, pos);
        result[1] = Arrays.copyOfRange(input, pos + 1, len);

well this is even not a java-method, but it explains how to get the result. in the example above, the result would be a 2-d array, [[one, two, three], [five, six, seven, eight]]

EDIT:

wrap it in a method is easy:

public static String[][] splitStringArray(String[] input, int pos) {
        final int len = input.length;
        final String[][] result = new String[2][Math.max(pos, len - pos - 1)];
        result[0] = Arrays.copyOf(input, pos);
        result[1] = Arrays.copyOfRange(input, pos + 1, len);
        return result;
    }

Note that error handling part is not there, e.g. pos outofbound handling, NPE checking (input) etc. you could do it by yourself I believe.

Upvotes: 1

Juvanis
Juvanis

Reputation: 25950

You can use ArrayList instead of array. Removing a random element from an arraylist is quite easy since it is dynamic.

ArrayList>String> list = new ArrayList<String>();
...
list.remove(1);

Upvotes: 5

Related Questions