Home  >  Article  >  Java  >  How to Split a String at Every N-th Character in Java?

How to Split a String at Every N-th Character in Java?

DDD
DDDOriginal
2024-11-21 13:06:10609browse

How to Split a String at Every N-th Character in Java?

Splitting Strings at Every N-th Character

In programming, it is often necessary to split a string into individual characters or substrings. JavaScript provides a convenient way to split a string at every n-th character using the .match() method. However, in Java, achieving the same result requires a slightly different approach.

Java Solution

To split a string at every n-th character in Java, you can utilize the following code:

String s = "1234567890";
System.out.println(java.util.Arrays.toString(s.split("(?<=\G...)")));

This code employs the following techniques:

  • Split() Method: Divides the string into substrings based on a given delimiter.
  • Regular Expression: The delimiter uses a regular expression to define the splitting criteria.
  • (?<=G...) Regex: Captures an empty string that matches the previous match followed by three characters.

This allows you to split the string "1234567890" into the following substrings:

[123, 456, 789, 0]

The resulting list of substrings accurately reflects the desired splitting into 3-character segments.

The above is the detailed content of How to Split a String at Every N-th Character in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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