我需要在Java中连接两个字符串数组。
void f(String[] first, String[] second) {
String[] both = ???
}
哪种方法最简单?
我需要在Java中连接两个字符串数组。
void f(String[] first, String[] second) {
String[] both = ???
}
哪种方法最简单?
当前回答
我有一个简单的方法。您不想浪费时间研究复杂的java函数或库。但返回类型应该是String。
String[] f(String[] first, String[] second) {
// Variable declaration part
int len1 = first.length;
int len2 = second.length;
int lenNew = len1 + len2;
String[] both = new String[len1+len2];
// For loop to fill the array "both"
for (int i=0 ; i<lenNew ; i++){
if (i<len1) {
both[i] = first[i];
} else {
both[i] = second[i-len1];
}
}
return both;
}
这么简单。。。
其他回答
我有一个简单的方法。您不想浪费时间研究复杂的java函数或库。但返回类型应该是String。
String[] f(String[] first, String[] second) {
// Variable declaration part
int len1 = first.length;
int len2 = second.length;
int lenNew = len1 + len2;
String[] both = new String[len1+len2];
// For loop to fill the array "both"
for (int i=0 ; i<lenNew ; i++){
if (i<len1) {
both[i] = first[i];
} else {
both[i] = second[i-len1];
}
}
return both;
}
这么简单。。。
这里是silvertab解决方案的一个修改,对泛型进行了改进:
static <T> T[] concat(T[] a, T[] b) {
final int alen = a.length;
final int blen = b.length;
final T[] result = (T[]) java.lang.reflect.Array.
newInstance(a.getClass().getComponentType(), alen + blen);
System.arraycopy(a, 0, result, 0, alen);
System.arraycopy(b, 0, result, alen, blen);
return result;
}
注意:请参阅Joachim的Java 6解决方案答案。它不仅消除了警告;它也更短,更高效,更容易阅读!
我从老的Apache Commons Lang库中找到了一个单行解决方案。ArrayUtils.addAll(T[],T…)
代码:
String[] both = ArrayUtils.addAll(first, second);
这是算盘常用的密码。
String[] a = {"a", "b", "c"};
String[] b = {"1", "2", "3"};
String[] c = N.concat(a, b); // c = ["a", "b", "c", "1", "2", "3"]
// N.concat(...) is null-safety.
a = null;
c = N.concat(a, b); // c = ["1", "2", "3"]
ArrayList<String> both = new ArrayList(Arrays.asList(first));
both.addAll(Arrays.asList(second));
both.toArray(new String[0]);