1

Let's say I have the following string:

String = "0123456789abcdefg";

How can I split it in blocks of 5, so that I get an array of string like

["01234", "56789", "abcde", "fg"]

Notice the last string is 2 characters long.

Is there a simple way to do so in Java?

Gradient
  • 2,253
  • 6
  • 25
  • 36

2 Answers2

3
//UNTESTED CODE!!
String in = "0123456789abcdefg";
List<String> blocks = new ArrayList<String>();

int i = 0;
for ( ; i < (in.length()-5) ; i += 5) { //while there are more than 5 characters remaining 
    blocks.add(in.substring(i, (i+5) ); 
}

blocks.add(in.substring(i, in.length()) //add any remaining characters 
drew moore
  • 31,565
  • 17
  • 75
  • 112
  • +1 for the comments in your code (although I insist the OP should have tried first) – morgano Jul 09 '14 at 02:38
  • @morgano yeah I agree completely - I just felt like doing it. OP, this answer was a disservice to you. Next time you run into a problem like this, do everything you can to figure it out yourself - that's how you learn to program, because programming *is* figuring things like this out. Come to SO when what you've figured out isn't working. – drew moore Jul 09 '14 at 02:43
  • 1
    interesting thing is that, doing micro-benchark between your solution and the one-liner answer in the duplicate question, yours runs at least 5 times faster... ha... just saying... makes sense as in the one-liner a regex must have to be internally compiled, so moral of the story is shorter code doesn't mean more efficient – morgano Jul 09 '14 at 03:20
1

I guess that the substring method should be enough for your purpose, something like:

final int CHUNK_SIZE = 5;
List<String> chunks = new ArrayList<String>();

for (int i = 0; i*CHUNK_SIZE < string.length() - 1; ++i)
  chunks.add(string.substring(i*chunkSize,Math.min((i+1)*chunkSize, string.length())));
Jack
  • 131,802
  • 30
  • 241
  • 343