我有这个字符串数组str []可能很长。我想将它分成arraylists或数组,每个都有6个值,所以:
str1[] = [str[0], str[1], str[2], str[3], str[4], str[5]]
str2[] = [str[6], str[7], str[8], str[9], str[10], str[11]]
等等,我该怎么做?
答案 0 :(得分:1)
你需要一个2d字符串数组才能实现这一目标。
str = ... // this is your array of strings
chunks = str.length / 6;
String[][] strs = new String[chunks][6];
for (int i = 0; i < chunks; i++) {
for (int j = 0; j < 6; j++) {
strs[i][j] = str[i*6 + j];
}
}
答案 1 :(得分:0)
作为替代方法,您还可以使用System.arraycopy
,从而无需事先预先指定块或子阵列的数量。只需使用数组的ArrayList,如下所示:
ArrayList<String[]> arrays = new ArrayList<String[]>();
int arraySize = 3;
String[] first = new String[] { "a", "b", "c", "D", "E", "F", "g", "h",
"i", "J" };
for (int i = 0; i < first.length; i+=arraySize) {
String[] foo = new String[arraySize];
if (i + arraySize <= first.length) {
System.arraycopy(first, i, foo, 0, arraySize);
} else {
System.arraycopy(first, i, foo, 0, first.length - i);
}
arrays.add(foo);
}