Skip to content

Instantly share code, notes, and snippets.

@bmchild
Created August 18, 2014 18:09
Show Gist options
  • Save bmchild/c144983f126152a0738b to your computer and use it in GitHub Desktop.
Save bmchild/c144983f126152a0738b to your computer and use it in GitHub Desktop.
/**
* splits the string at every nth position
* @param str
* @param position
* @return a list of Strings each string has a length <= position
*/
public static List<String> splitEveryPosition(String str, Integer position) {
List<String> strings = new ArrayList<String>();
Integer length = str.length();
Integer actualPosition = Math.min(length, position);
for(int i = 0; i < length;) {
int toPos = i + actualPosition;
if(toPos > length) {
toPos = length;
}
strings.add( str.substring(i, toPos) );
i += actualPosition;
}
return strings;
}
@Test
public void testSplitEveryPosition_LargerPosition() throws Exception {
String str = "1234567890";
Integer position = 12;
List<String> split = StringUtils.splitEveryPosition(str, position);
assertEquals(1, split.size());
assertEquals(str, split.get(0));
}
@Test
public void testSplitEveryPosition() throws Exception {
String str = "12345678901";
Integer position = 2;
List<String> split = StringUtils.splitEveryPosition(str, position);
assertEquals(6, split.size());
assertEquals("12", split.get(0));
assertEquals("34", split.get(1));
assertEquals("56", split.get(2));
assertEquals("78", split.get(3));
assertEquals("90", split.get(4));
assertEquals("1", split.get(5));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment