Splitting a string into n-length elements for an array

How would I split a string into equal parts, using String.split()if the string is filled with numbers? For example, each part below has a size of 5.

"123" would be split into "123"
"12345" would be split into "12345"
"123451" would be split into "12345" and "1"
"123451234512345" would be split into "12345", "12345" and "12345"
etc

They should be placed in an array:

String myString = "12345678";
String[] myStringArray = myString.split(???);
//myStringArray => "12345", "678";

I just don’t know how to use the regular expression, and how to split it into equal sized pieces.

+4
source share
1 answer

You can try this way

String input = "123451234512345";
String[] pairs = input.split("(?<=\\G\\d{5})");
System.out.println(Arrays.toString(pairs));

Output:

[12345, 12345, 12345]

(?<=...) \\G, " ", , ( ) ^, ".

, , , , , .

+7

Source: https://habr.com/ru/post/1530846/


All Articles