StringWrapper { public static String[] wrapString(@Nonnull String str, int maxWidth, @Nullable String[] output) { if (output == null) { output = new String[(int)((str.length() / maxWidth) * 1.5d + 1)]; } int lineStart = 0; int arrayIndex = 0; int i; for (i=0; i<str.length(); i++) { char c = str.charAt(i); if (c == '\n') { output = addString(output, str.substring(lineStart, i), arrayIndex++); lineStart = i+1; } else if (i - lineStart == maxWidth) { output = addString(output, str.substring(lineStart, i), arrayIndex++); lineStart = i; } } if (lineStart != i || i == 0) { output = addString(output, str.substring(lineStart), arrayIndex++, output.length+1); } if (arrayIndex < output.length) { output[arrayIndex] = null; } return output; }  static Iterable<String> wrapStringOnBreaks(@Nonnull final String string, final int maxWidth); static String[] wrapString(@Nonnull String str, int maxWidth, @Nullable String[] output); static void printWrappedString(@Nonnull PrintStream stream, @Nonnull String string); static void printWrappedString(@Nonnull PrintStream stream, @Nonnull String string, int maxWidth);  }
@Test public void testWrapString() { validateResult( new String[]{"abc", "abcdef", "abcdef"}, StringWrapper.wrapString("abc\nabcdefabcdef", 6, null)); validateResult( new String[]{"abc"}, StringWrapper.wrapString("abc", 6, new String[3])); validateResult( new String[]{"abc"}, StringWrapper.wrapString("abc", 6, new String[0])); validateResult( new String[]{"abc"}, StringWrapper.wrapString("abc", 6, new String[1])); validateResult( new String[]{""}, StringWrapper.wrapString("", 6, new String[3])); validateResult( new String[]{"abcdef"}, StringWrapper.wrapString("abcdef", 6, new String[3])); validateResult( new String[]{"abcdef", "abcdef"}, StringWrapper.wrapString("abcdef\nabcdef", 6, new String[3])); validateResult( new String[]{"abc", "", "def"}, StringWrapper.wrapString("abc\n\ndef", 6, new String[3])); validateResult( new String[]{"", "abcdef"}, StringWrapper.wrapString("\nabcdef", 6, new String[3])); validateResult( new String[]{"", "", "abcdef"}, StringWrapper.wrapString("\n\nabcdef", 6, new String[3])); validateResult( new String[]{"", "", "abcdef"}, StringWrapper.wrapString("\n\nabcdef", 6, new String[4])); validateResult( new String[]{"", "", "abcdef", ""}, StringWrapper.wrapString("\n\nabcdef\n\n", 6, new String[4])); validateResult( new String[]{"", "", "abcdef", "a", ""}, StringWrapper.wrapString("\n\nabcdefa\n\n", 6, new String[4])); validateResult( new String[]{"", "", "abcdef", "a", ""}, StringWrapper.wrapString("\n\nabcdefa\n\n", 6, new String[0])); validateResult( new String[]{"", "", "abcdef", "a", ""}, StringWrapper.wrapString("\n\nabcdefa\n\n", 6, new String[5])); validateResult( new String[]{"", "", "a", "b", "c", "d", "e", "f", "a", ""}, StringWrapper.wrapString("\n\nabcdefa\n\n", 1, new String[5])); }