Home > Java > javaTutorial > How to Split a String into Chunks at Regular Intervals in Java?

How to Split a String into Chunks at Regular Intervals in Java?

Susan Sarandon
Release: 2024-11-13 13:43:02
Original
354 people have browsed it

How to Split a String into Chunks at Regular Intervals in Java?

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)
Copy after login

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...)")));
Copy after login

Explanation of the Regex:

The regular expression used in this solution is:

(?<=\G...)
Copy after login

This regex consists of the following components:

  • (?<=G): Matches an empty string at the end of the previous match.
  • ...: Matches any three characters.
  • (?<= ): Ensures that the pattern matches only if it is preceded by the three characters.

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]
Copy after login

This demonstrates that the string has been successfully divided into chunks of three characters each.

The above is the detailed content of How to Split a String into Chunks at Regular Intervals in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template