簡體   English   中英

如何在Java中連接兩個字符串數組

[英]How to concat two string arrays in Java

我正在使用JDK 1.7和Eclipse並嘗試連接兩個字符串數組:

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

我試過了

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

進口

import com.google.common.collect.ObjectArrays;

得到錯誤:

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

有人可以幫忙嗎? 我正在使用Maven來構建項目。

import類型是不夠的。 編譯代碼時,需要在類路徑上實際提供該類型。

它似乎

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

就像你沒有在類路徑中提供包含上述類型的jar

或者你也可以這樣做

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

這段代碼應該有效。 不像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);

下載common.codec-1.9.jar (下載zip並解壓縮,你會找到jar文件)然后如果你正在使用像IDE這樣的IDE

日食:

1.右鍵單擊您的項目。

2.選擇屬性。

3.在左側單擊java構建路徑。

4.在Libraries選項卡下,單擊Add External Jars按鈕。

5.選擇下載的文件,然后單擊“確定”

Netbeans:

1.右鍵單擊您的項目。

2.選擇屬性。

3.在左側單擊“庫”。

4.在“編譯”選項卡下 - 單擊“添加Jar /文件夾”按鈕。

將正確的Maven依賴項添加到您的POM:

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

為什么不進行for循環並將所有元素存儲到一個String然后使用.split?

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

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

我從紙上做了這個,但我幾乎肯定它會起作用;)

我發現避免arrayCopy()和copyOf()中所有startingIndex和endingIndex參數的最簡單方法是編寫一個特定的方法(這很簡單):

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().

所以這里是concatTwoStringArrays()方法的用法:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM