Split a string at every 4-th character?

Trillian :

I have a string which i have to split into substrings of equal length if possible. I have found this solution which will only work if the string length is a multiple of 4.

String   myString = "abcdefghijklm";
String[] split = myString.split("(?<=\\G....)");

This will produce:

[abcd, efgh, ijkl, m]

What i need is to split "from the end of the string". My desired output should look like :

[a, bcde, fghi, jklm]

How do i achieve this?

Bart Kiers :

This ought to do it:

String[] split = myString.split("(?=(....)+$)");
// or
String[] split = myString.split("(?=(.{4})+$)");

What it does is this: split on the empty string only if that empty string has a multiple of 4 chars ahead of it until the end-of-input is reached.

Of course, this has a bad runtime (O(n^2)). You can get a linear running time algorithm by simply splitting it yourself.

As mentioned by @anubhava:

(?!^)(?=(?:.{4})+$) to avoid empty results if string length is in multiples of 4

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=85357&siteId=1