我需要在Java中合并两个String
数组。
void f(String[] first, String[] second) {
String[] both = ???
}
最简单的方法是什么?
我需要在Java中合并两个String
数组。
void f(String[] first, String[] second) {
String[] both = ???
}
最简单的方法是什么?
只是想补充一下,你也可以使用 System.arraycopy
:
import static java.lang.System.out;
import static java.lang.System.arraycopy;
import java.lang.reflect.Array;
class Playground {
@SuppressWarnings("unchecked")
public static <T>T[] combineArrays(T[] a1, T[] a2) {
T[] result = (T[]) Array.newInstance(a1.getClass().getComponentType(), a1.length+a2.length);
arraycopy(a1,0,result,0,a1.length);
arraycopy(a2,0,result,a1.length,a2.length);
return result;
}
public static void main(String[ ] args) {
String monthsString = "JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC";
String[] months = monthsString.split("(?<=\\G.{3})");
String daysString = "SUNMONTUEWEDTHUFRISAT";
String[] days = daysString.split("(?<=\\G.{3})");
for (String m : months) {
out.println(m);
}
out.println("===");
for (String d : days) {
out.println(d);
}
out.println("===");
String[] results = combineArrays(months, days);
for (String r : results) {
out.println(r);
}
out.println("===");
}
}
看看这个优雅的解决方案(如果你需要其他类型而不是char,请更改它):
private static void concatArrays(char[] destination, char[]... sources) {
int currPos = 0;
for (char[] source : sources) {
int length = source.length;
System.arraycopy(source, 0, destination, currPos, length);
currPos += length;
}
}
您可以连接任意数量的数组。
应该可以解决问题。这是假设 String[] first 和 String[] second 的情况。
List<String> myList = new ArrayList<String>(Arrays.asList(first));
myList.addAll(new ArrayList<String>(Arrays.asList(second)));
String[] both = myList.toArray(new String[myList.size()]);
myList.addAll(new ArrayList<String>(Arrays.asList(second)));
can be simplified to myList.addAll(Arrays.asList(second))
- slartidan[a, b, c] ++ [d, e]
以获取[a, b, c, d, e]
。 这些是Haskell列表连接起来的,但是如果Java有一个类似的运算符来操作数组将非常好。 您不认为吗?这很优雅,简单,通用,并且实现起来并不那么困难。i ** j = Math.pow(i, j)
。 可以借鉴这个例子来实现一个连接两个相同类型数组的运算符。一旦你这样做了,你就会被绑定到你自定义的javac来编译你的代码,但生成的字节码将被任何JVM理解。
当然,你可以在源代码级别实现自己的数组连接方法,在其他答案中有许多示例!
有很多有用的运算符可以添加,这个运算符将是其中之一。
void f(String[] first, String[] second) {
String[] both = new String[first.length+second.length];
for(int i=0;i<first.length;i++)
both[i] = first[i];
for(int i=0;i<second.length;i++)
both[first.length + i] = second[i];
}
这个方法不需要任何其他类/库的知识。
它适用于任何数据类型。只需将String
替换为任何东西,如int
、double
或char
。
它的效率相当高。
这是对我有用的内容:
String[] data=null;
String[] data2=null;
ArrayList<String> data1 = new ArrayList<String>();
for(int i=0; i<2;i++) {
data2 = input.readLine().split(",");
data1.addAll(Arrays.asList(data2));
data= data1.toArray(new String[data1.size()]);
}
array1 + array2
连接函数。 - JollyJoker