Splitting a string into equal parts (java / groovy)

I would like to split a string into substrings with 20 characters (or less for the tail). Is there any library or do I need to make a class for this?

+1
source share
2 answers

you should use:

s.split("(?<=\\G.{20})");

\Gis a zero-width statement that corresponds to the position at which the previous match ended. If there was no previous match, it matches the beginning of the input, just like \A. The attached lookbehind corresponds to a position consisting of 20 characters from the end of the last match.

+10
source

Or, with Groovy you can do:

assert 'abcdefghij'.toList().collate( 3 )*.join() == ['abc', 'def', 'ghi', 'j']
+3
source

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


All Articles