这可以通过将字符串拆分为包含单个元素的列表,将其划分为三个一组,然后将每个分区中的元素重新连接在一起来实现。
String s_prices = "19; 16; 20; 01; 16; 1.3; 1.6; 50; 2.0; 17";
// Convert to List of strings:
// ["19", "16", "20", "01", "16", "1.3", "1.6", "50", "2.0", "17"]
List<String> prices = Arrays.asList(s_prices.split("; "));
// Convert to List of 3-element lists of strings (possibly fewer for last one):
// [["19", "16", "20"], ["01", "16", "1.3"], ["1.6", "50", "2.0"], ["17"]]
List<List<String>> partitions = new ArrayList<>();
for (int i = 0; i < prices.size(); i += 3) {
partitions.add(prices.subList(i, Math.min(i + 3, prices.size())));
}
// Convert each partition List to a comma-delimited string
// ["13, 16, 20", "01, 16, 1.3", "1.6, 50, 2.0", "17"]
List<String> substrings =
partitions.stream().map(p -> String.join(", ", p)).toList();
// Output each list element on a new line to view the results
System.out.println(String.join("\n", substrings));
输出:
19, 16, 20
01, 16, 1.3
1.6, 50, 2.0
17