简体   繁体   English

在Java中拆分字符串数组

[英]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"]] 例如,对于字符串数组["Good","Bad","Sad"]如果我将其分割为1,它会给我一个看起来像这样的字符串矩阵[["Good"],["Sad"]]

You can use ArrayList instead of array. 您可以使用ArrayList代替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). 伊万诺维奇的答案很好地解释了如何使用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. 但是,我对OP问题的理解是,他获得了一个字符串数组作为参数,并希望返回一个二维String数组。 the "split-index" element should not be included in the result String[][]. 结果“ String [] []”中不应包含“ split-index”元素。

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. 好吧,这甚至不是Java方法,但它说明了如何获得结果。 in the example above, the result would be a 2-d array, [[one, two, three], [five, six, seven, eight]] 在上面的示例中,结果将是一个[[one, two, three], [five, six, seven, eight]]数组, [[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. 请注意,错误处理部分不存在,例如pos出站处理,NPE检查(输入)等。我相信您可以自己完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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