Tuesday, July 23, 2013

Split String into Fixed Length chunks using Java

I needed to split a large string into fixed length chunks of equal size using Java Apart from the regular method of looping and doing a substring for the required length, I was wondering in what other way was it possible to achieve the same. Of course, it's Mr. Regex to the rescue for this task at hand! Here was the regex I used to do this:
String largeString = "This is a very large and totally useless and meaningless string";
int chunkLength = 5;
String[] chunks = largeString.split("(?<=\\G.{" + chunkLength + "})");
System.out.println("Number of chunks: " + chunks.length); // Should print 13
System.out.println("Chunk size: " + chunks[0].size()); // Should print 5 == chunkLength
The regular expression is a Positive Look-Behind looking for any chunkLength characters beginning at the position where the last match ended. So the first time around, it matches the beginning of the string and then after that, it keeps matching every set of chunkLength characters.
This makes me think I should write a more detailed post about regular expressions, especially on Look-Ahead and Look-Behind - stay tuned!


john kevin said...

Thanks a lot very much for the high quality and results-oriented help. I won’t think twice to endorse your blog post to anybody who wants and needs support about this area.

java training in bangalore

anudeep bichal said...

Needed to compose you a very little word to thank you yet again regarding the nice suggestions you’ve contributed here.

java training in bangalore

srihariparu said...

Thank you for sharing your helpful post with us..keep updating..
Robotics Project Center in Chennai | Best Robotics Projects in Chennai | IEEE Robotics Project Center in Chennai | No.1 Robotics Project Center in Velachery

Gowri S said...

It has been just unfathomably liberal with you to give straightforwardly what precisely numerous people would've promoted for an eBook to wind up making some money for their end, basically given that you could have attempted it in the occasion you needed.
big data training in bangalore

raina dhawan said...

It’s great to come across a blog every once in a while that isn’t
the same out of date rehashed material. Fantastic read.
dotnet training in chennai


Related Posts Plugin for WordPress, Blogger...