3 回答

TA貢獻(xiàn)1789條經(jīng)驗(yàn) 獲得超10個(gè)贊
這是一個(gè)使用流的 Java 8 解決方案。邏輯是首先用逗號(hào)分割輸入字符串,生成一個(gè)術(shù)語數(shù)組。然后,對(duì)于每個(gè)術(shù)語,我們?cè)?dash 上再次拆分,保留第一個(gè)條目。對(duì)于沒有破折號(hào)的術(shù)語,將只保留整個(gè)字符串。最后,我們連接回輸出字符串。
String input = "aa-bb,ccdd,eeff,gg-gg,cc-gg";
int pos = 1;
String output = String.join(",", Arrays.stream(parts)
.map(e -> e.split("-").length >= (pos+1) ? e.split("-")[pos] : "0")
.toArray(String[]::new));
System.out.println(output);
這輸出:
bb,0,0,gg,gg

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超3個(gè)贊
List<String> list1 = new ArrayList<>();
List<String> list2 = new ArrayList<>();
// First split the source String by comma to separate main parts
String[] mainParts = sourceStr.split(",");
for (String mainPart: mainParts) {
// Check if each part contains '-' character
if (mainPart.contains("-")) {
// If contains '-', split and add the 2 parts to 2 arrays
String[] subParts = mainPart.split("-");
list1.add(subParts[0]);
list2.add(subParts[1]);
} else {
// If does not contain '-', add complete part to 1st array and add placeholder to 2nd array
list1.add(mainPart);
list2.add("0");
}
}
// Build the final Strings by joining String parts by commas and enclosing between parentheses
String str1 = "{" + String.join(",", list1) + "}";
String str2 = "{" + String.join(",", list2) + "}";
System.out.println(str1);
System.out.println(str2);

TA貢獻(xiàn)1811條經(jīng)驗(yàn) 獲得超5個(gè)贊
我認(rèn)為這可以解決您的問題。
private static void splitStrings() {
List<String> list = Arrays.asList("aa-bb", "ccdd", "eeff", "gg-gg", "cc-gg");
List firstPartList = new ArrayList<>();
List secondPartList = new ArrayList<>();
for (String undividedString : list){
if(undividedString.contains("-")){
String[] dividedParts = undividedString.split("-");
String firstPart = dividedParts[0];
String secondPart = dividedParts[1];
firstPartList.add(firstPart);
secondPartList.add(secondPart);
} else{
firstPartList.add(undividedString);
secondPartList.add("0");
}
}
System.out.println(firstPartList);
System.out.println(secondPartList);
}
輸出是 -
[aa, ccdd, eeff, gg, cc]
[bb, 0, 0, gg, gg]
添加回答
舉報(bào)