如何将包含文本字符串的所有数组连接或附加到单个数组中?从以下代码:
String nList[] = {"indonesia", "thailand", "australia"};
int nIndex[] = {100, 220, 100};
String vkList[] = {"wounded", "hurt"};
int vkIndex[] = {309, 430, 550};
String skList[] = {"robbed", "detained"};
int skIndex[] = {120, 225};
String nationality = "";
//System.out.println(nationality);
我想存储所有三个包含字符串的数组的所有字符串:
String nList[] = {"indonesia", "thailand", "australia"};
String vkList[] = {"wounded", "hurt"};
String skList[] = {"robbed", "detained"};
成一个数组,比如array1 []。
答案 0 :(得分:0)
ArrayList<String> temp = new ArrayList<String>();
temp.addAll(Arrays.asList(nList));
temp.addAll(Arrays.asList(vkList));
temp.addAll(Arrays.asList(skList));
String[] result = (String[])temp.toArray();
答案 1 :(得分:0)
您可以将每个数组的内容添加到临时List
,然后将其内容转换为String[]
。
List<String> temp = new ArrayList<String>();
temp.addAll(Arrays.asList(nList));
temp.addAll(Arrays.asList(vkList));
temp.addAll(Arrays.asList(skList));
String[] result = new String[temp.size()];
for (int i = 0; i < temp.size(); i++) {
result[i] = (String) temp.get(i);
}
或者,您可以使用Guava的ObjectArrays#concat(T[] first, T[] second, Class< T > type)方法,该方法返回一个包含两个给定数组的连接内容的新数组。例如:
String[] concatTwoArrays = ObjectArrays.concat(nList, vkList, String.class);
String[] concatTheThirdArray = ObjectArrays.concat(concatTwoArrays, skList, String.class);
答案 2 :(得分:0)
public static String[] join(String [] ... parms) {
// calculate size of target array
int size = 0;
for (String[] array : parms) {
size += array.length;
}
String[] result = new String[size];
int j = 0;
for (String[] array : parms) {
for (String s : array) {
result[j++] = s;
}
}
return result;
}
只需定义自己的连接方法即可。找到@ http://www.rgagnon.com/javadetails/java-0636.html