diff --git a/src/main/java/strman/Strman.java b/src/main/java/strman/Strman.java index 83d4808..6598b0b 100644 --- a/src/main/java/strman/Strman.java +++ b/src/main/java/strman/Strman.java @@ -1389,6 +1389,21 @@ public abstract class Strman { return resultBuilder.toString(); } + public static String[] chop(String input, int step) { + if (input == null || input.length() == 0) { + return EMPTY_ARRAY; + } + if (step == 0) { + return new String[]{input}; + } + int strLength = input.length(); + int iterations = strLength % step == 0 ? strLength / step : strLength / step + 1; + return IntStream.iterate(0, i -> i + step) + .limit(iterations) + .mapToObj(i -> input.substring(i, (i + step) < strLength ? i + step : strLength)) + .toArray(String[]::new); + } + private static void validate(String value, Predicate predicate, final Supplier supplier) { if (predicate.test(value)) { throw new IllegalArgumentException(supplier.get()); diff --git a/src/test/java/strman/StrmanTests.java b/src/test/java/strman/StrmanTests.java index 73f9dcd..7945b20 100644 --- a/src/test/java/strman/StrmanTests.java +++ b/src/test/java/strman/StrmanTests.java @@ -1176,4 +1176,12 @@ public class StrmanTests { assertThat(swapCase(""), equalTo("")); assertThat(swapCase(null), equalTo("")); } + + @Test + public void chop_shouldChopStringByStep() throws Exception { + assertThat(chop(null, 2).length, equalTo(0)); + assertThat(chop("whitespace", 2).length, equalTo(5)); + assertThat(chop("whitespace", 3).length, equalTo(4)); + assertThat(chop("whitespace", 0)[0].length(), equalTo(10)); + } }