简体   繁体   中英

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"]]

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);

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, eg pos outofbound handling, NPE checking (input) etc. you could do it by yourself I believe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM