如何将分隔元素的字符串拆分为包含相同数量元素的子字符串?

How to split a string of delimited elements into substrings containing an equal number of elements?

我有一个很长的字符串,价格在40万左右甚至更多..

String s_prices = "19; 16; 20; 01; 16; 1.3; 1.6; 50; 2.0; 17; ..."

然后从这个很长的字符串中,我想把它分成多个子字符串,每个子字符串应该有3个价格,例如:

19, 16, 20 

01, 16, 1.3

1.6, 50, 2.0 

and more...

如何创建每个都包含三个价格的子字符串?

这可以通过将字符串拆分为包含各个元素的列表,将其分成三个一组,然后将每个分区中的元素重新组合在一起来实现。

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