>  기사  >  Java  >  Java에서 일정한 간격으로 문자열을 분할하는 방법은 무엇입니까?

Java에서 일정한 간격으로 문자열을 분할하는 방법은 무엇입니까?

Patricia Arquette
Patricia Arquette원래의
2024-11-15 04:04:02292검색

How to Split a String at Regular Intervals in Java?

Splitting Strings at Regular Intervals in Java

Splitting a string at every n-th character is a common operation in programming. In Java, there exist multiple ways to achieve this. However, one effective approach is to utilize the split() method, which allows for fine-tuning the splitting behavior.

Similar to the example provided in JavaScript, where a string is split into groups of three characters, we can replicate this functionality in Java using the following snippet:

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

This code achieves the desired result by splitting the string s at every third character. The split() method takes a regular expression as its parameter, and the expression provided in this case is:

(?<=\\G...)

Understanding the Regular Expression

Breaking down the regular expression part by part:

  • (?<= and ): These define a lookbehind assertion, which matches an empty string that appears after a specific pattern.
  • \G: This matches the end of the previous match, effectively acting as an anchor at the start of every third character.
  • ...: This matches any three characters.

Explanation

The split() method utilizes the pattern provided in the regular expression to identify the split points within the string. The lookbehind assertion ensures that the split occurs at positions that have three consecutive characters preceding them. The \G anchor helps maintain the correct split points as the method progresses through the string.

As a result, the output of the code is:

[123, 456, 789, 0]

This demonstrates how to effectively split a string at every n-th character in Java using the split() method and a custom regular expression.

위 내용은 Java에서 일정한 간격으로 문자열을 분할하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.