Dividing a String into Chunks at Specified Intervals using Java
In Java, splitting a string at regular intervals can be achieved using regular expressions.
For instance, the provided problem demonstrates how to divide a string "foobarspam" into chunks of three characters in JavaScript:
"foobarspam".match(/.{1,3}/g)
Java Implementation:
To replicate this functionality in Java, one can employ the following approach:
String s = "1234567890"; System.out.println(java.util.Arrays.toString(s.split("(?<=\\G...)")));
Explanation of the Regex:
The regular expression used in this solution is:
(?<=\G...)
This regex consists of the following components:
Therefore, this regex matches an empty string that has the last match followed by three characters before it. This allows for the desired splitting of the string.
Output:
When the above Java code is executed using the sample string "1234567890", it produces the following output:
[123, 456, 789, 0]
This demonstrates that the string has been successfully divided into chunks of three characters each.
以上是如何在 Java 中定期将字符串拆分为块?的详细内容。更多信息请关注PHP中文网其他相关文章!