How to concatenate two string arrays in Java

I am using JDK 1.7 and Eclipse and trying to execute two string arrays:

String [] a1 = { "a12", "b12" };
String [] a2 = { "c12", "d23", "ewe", "fdfsd" };

I tried

String[] both = ObjectArrays.concat(a1,a2,String.class); 

imported

import com.google.common.collect.ObjectArrays;

getting error:

can not resolve "import com.google.common.collect.ObjectArrays"

Can anyone help? I use Maven to create a project.

+4
source share
7 answers

Not enough importtype. You should actually provide this type in the classpath when compiling your code.

It seems

can not resolve "import org.apache.commons.lang3.ArrayUtil"

as you did not specify jar, containing the type indicated above in your classpath.

+6
source

Alternatively you can do it this way

    String[] a3 = Arrays.copyOf(a1, a1.length + a2.length);
    System.arraycopy(a2, 0, a3, a1.length, a2.length);
+3
source

. , ArrayUtils.addAll(), . -, .

String[] both = new String[a1.length + a2.length];
System.arraycopy(a1,0,both,0, a1.length);
System.arraycopy(a2,0,both,a1.length + 1, a2.length);
+2

for , .split?

String result = null;
for(String aux : a1){
   final += aux + ";";
}

for(String aux1 : a2){
   final += aux1 + ";";
}
String[] finalArray= result.split(";");

, , ;)

0

common.codec-1.9.jar ( zip jar), if IDE,

Eclipse:

1. .

2. "".

3. java.

4.Under Libraries Add External Jars.

5. ok

Netbeans:

1. .

2. "".

3. "".

4. - Jar/Folder.

0

Maven POM:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.3.2</version>
</dependency>
0
source

I found that the easiest way to avoid all the startIndex and endIndex parameters in arrayCopy () and copyOf () is to write a specific method (which directly):

public static String[] concatTwoStringArrays(String[] s1, String[] s2){
    String[] result = new String[s1.length+s2.length];
    int i;
    for (i=0; i<s1.length; i++)
        result[i] = s1[i];
    int tempIndex =s1.length; 
    for (i=0; i<s2.length; i++)
        result[tempIndex+i] = s2[i];
    return result;
}//concatTwoStringArrays().

So here the concatTwoStringArrays () method is used:

String[] s3 = concatTwoStringArrays(s1, s2);
0
source

Source: https://habr.com/ru/post/1537929/


All Articles