I use this regex to split a string at every say 3rd position:
String []thisCombo2 = thisCombo.split("(?<=\\G...)");
where the 3 dots after the G indicates every nth position to split. In this case, the 3 dots indicate every 3 positions. An example:
Input: String st = "123124125134135145234235245"
Output: 123 124 125 134 135 145 234 235 245.
My question is, how do i let the user control the number of positions where the string must be split at? In other words, how do I make those 3 dots, n dots controlled by the user?
Using Google Guava, you can use Splitter.fixedLength()
If you want to build that regex string you can set the split length as a parameter.
For a big performance improvement, an alternative would be to use
substring()
in a loop:Example:
It's not as short as stevevls' solution, but it's way more efficient (see below) and I think it would be easier to adjust in the future, of course depending on your situation.
Performance tests (Java 7u45)
2,000 characters long string - interval is 3.
split("(?<=\\G.{" + count + "})")
performance (in miliseconds):splitStringEvery()
(substring()
) performance (in miliseconds):2,000,000 characters long string - interval is 3.
split()
performance (in miliseconds):splitStringEvery()
performance (in miliseconds):2,000,000 characters long string - interval is 30.
split()
performance (in miliseconds):splitStringEvery()
performance (in miliseconds):Conclusion:
The
splitStringEvery()
method is a lot faster (even after the changes in Java 7u6), and it escalates when the intervals become higher.Ready-to-use Test Code:
pastebin.com/QMPgLbG9
You can use the brace operator to specify the number of times a character must occur:
The brace is a handy tool because you can use it to specify either an exact count or ranges.