如何将两个“if”子句中的两个数组合并在一起

时间:2014-03-24 02:25:41

标签: java arrays merge concatenation

我从文本文件解析了2个数组:

if (line.startsWith("#dataOne ")){  
    String[] oneS = line.split("= ");                   
    String[]oneT= oneS[1].split(" ");
   // System.out.println(Arrays.toString(oneT));            
}

if (line.startsWith("#dataFour")){
    String[] twoS = line.split("= ");   
    String[]twoSets= twoS[1].split(", ");                  
    // System.out.println(Arrays.toString(twoSets));
} 

如何将oneTtwoSets合并在一起?

1 个答案:

答案 0 :(得分:0)

我认为最简单的方法是使用List<String>来保存两个数组。你可以这样做:

List<String> merged = new ArrayList<>();
if (line.startsWith("#dataOne ")){  
    String[] oneS = line.split("= ");                
    String[]oneT= oneS[1].split(" ");
    merged.addAll(Arrays.asList(oneT));
}

if (line.startsWith("#dataFour")){
    String[] twoS = line.split("= ");   
    String[]twoSets= twoS[1].split(", ");                  
    merged.addAll(Arrays.asList(twoSets));
} 

如果您真的需要数组而不是String[],那么您可以将其转换为List。或者您可以先将merged的元素添加到Set以删除重复项。

或者,您可以在oneT块外部设置twoSetsif,然后使用String[]将它们直接合并到System.arraycopy

String[] oneT;
String[] twoSets;
if (line.startsWith("#dataOne ")){  
    String[] oneS = line.split("= ");                
    oneT= oneS[1].split(" ");
} else {
    oneT = new String[0];
}

if (line.startsWith("#dataFour")){
    String[] twoS = line.split("= ");   
    twoSets= twoS[1].split(", ");                  
} else {
    twoSets = new String[0];
} 

String[] merged = new String[oneT.length + twoSets.length];
System.arraycopy(oneT, 0, merged, 0, oneT.length);
System.arraycopy(twoSets, 0, merged, oneT.length, twoSets.length);