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!

1 comment:

Drupal Hosting said...

You make a great point. Got some great information here. I think that if more people thought about it that way, theyd have a better time understanding the issue. Your view is definitely something Id like to see more of. Thanks for this blog. Its fantastic and so is what youve got to say. Deciding upon a content management system is highly vital to your success I now only use Drupal. Because As I researched and found out the most popular universities in the US use Durpal, I picked Drupal For hosting I like Pantheon with features like Drush integrations What content management system do you like?

LinkWithin

Related Posts Plugin for WordPress, Blogger...