首頁 > Java > java教程 > 主體

如何在 Java 中定期將字串拆分為區塊?

Susan Sarandon
發布: 2024-11-13 13:43:02
原創
319 人瀏覽過

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)
登入後複製

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:

  • (?<=\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]
登入後複製

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

以上是如何在 Java 中定期將字串拆分為區塊?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板