我从文本文件解析了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));
}
如何将oneT
和twoSets
合并在一起?
答案 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
块外部设置twoSets
和if
,然后使用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);