我需要在Java中连接两个字符串数组。

void f(String[] first, String[] second) {
    String[] both = ???
}

哪种方法最简单?


当前回答

每个答案都是复制数据并创建新阵列。这并不是绝对必要的,如果您的阵列相当大,这绝对不是您想要做的。Java创建者已经知道数组拷贝是浪费的,这就是为什么他们提供System.arrayCopy()来在我们必须时在Java之外进行这些拷贝的原因。

与其四处复制数据,不如考虑将其保留在原地,并从中提取数据所在的位置。仅仅因为程序员想组织数据位置而复制数据位置并不总是明智的。

// I have arrayA and arrayB; would like to treat them as concatenated
// but leave my damn bytes where they are!
Object accessElement ( int index ) {
     if ( index < 0 ) throw new ArrayIndexOutOfBoundsException(...);
     // is reading from the head part?
     if ( index < arrayA.length )
          return arrayA[ index ];
     // is reading from the tail part?
     if ( index < ( arrayA.length + arrayB.length ) )
          return arrayB[ index - arrayA.length ];
     throw new ArrayIndexOutOfBoundsException(...); // index too large
}

其他回答

算法爱好者的另一个答案是:

public static String[] mergeArrays(String[] array1, String[] array2) {
    int totalSize = array1.length + array2.length; // Get total size
    String[] merged = new String[totalSize]; // Create new array
    // Loop over the total size
    for (int i = 0; i < totalSize; i++) {
        if (i < array1.length) // If the current position is less than the length of the first array, take value from first array
            merged[i] = array1[i]; // Position in first array is the current position

        else // If current position is equal or greater than the first array, take value from second array.
            merged[i] = array2[i - array1.length]; // Position in second array is current position minus length of first array.
    }

    return merged;

用法:

String[] array1str = new String[]{"a", "b", "c", "d"}; 
String[] array2str = new String[]{"e", "f", "g", "h", "i"};
String[] listTotalstr = mergeArrays(array1str, array2str);
System.out.println(Arrays.toString(listTotalstr));

结果:

[a, b, c, d, e, f, g, h, i]

这应该是一个衬垫。

public String [] concatenate (final String array1[], final String array2[])
{
    return Stream.concat(Stream.of(array1), Stream.of(array2)).toArray(String[]::new);
}

我刚刚发现了这个问题,很抱歉,很晚了,我看到了很多太遥远的答案,使用某些库,使用将数据从数组转换为流并返回到数组等功能。但是,我们只需要使用一个简单的循环,问题就解决了

public String[] concat(String[] firstArr,String[] secondArr){
        //if both is empty just return
        if(firstArr.length==0 && secondArr.length==0)return new String[0];

        String[] res = new String[firstArr.length+secondArr.length];
        int idxFromFirst=0;

        //loop over firstArr, idxFromFirst will be used as starting offset for secondArr
        for(int i=0;i<firstArr.length;i++){
            res[i] = firstArr[i];
            idxFromFirst++;
        }

        //loop over secondArr, with starting offset idxFromFirst (the offset track from first array)
        for(int i=0;i<secondArr.length;i++){
            res[idxFromFirst+i]=secondArr[i];
        }

        return res;
    }

就这样,对吧?他没有说他关心订单或任何事情。这应该是最简单的方法。

使用流的Java8的另一种方式

  public String[] concatString(String[] a, String[] b){ 
    Stream<String> streamA = Arrays.stream(a);
    Stream<String> streamB = Arrays.stream(b);
    return Stream.concat(streamA, streamB).toArray(String[]::new); 
  }
    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等任意值。它的工作效率很高。