Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static String wrap(final String str, int wrapLength,
- String newLineStr, final boolean wrapLongWords) {
- if (str == null) {
- return null;
- }
- if (newLineStr == null) {
- newLineStr = System.getProperty("line.separator");
- }
- if (wrapLength < 1) {
- wrapLength = 1;
- }
- final int inputLineLength = str.length();
- int offset = 0;
- final StringBuilder wrappedLine = new StringBuilder(
- inputLineLength + 32);
- while (inputLineLength - offset > wrapLength) {
- if (str.charAt(offset) == ' ') {
- offset++;
- continue;
- }
- int spaceToWrapAt = str.lastIndexOf(' ', wrapLength + offset);
- if (spaceToWrapAt >= offset) {
- // normal case
- wrappedLine.append(str.substring(offset, spaceToWrapAt));
- wrappedLine.append(newLineStr);
- offset = spaceToWrapAt + 1;
- } else {
- // really long word or URL
- if (wrapLongWords) {
- // wrap really long word one line at a time
- wrappedLine.append(str.substring(offset, wrapLength
- + offset));
- wrappedLine.append(newLineStr);
- offset += wrapLength;
- } else {
- // do not wrap really long word, just extend beyond limit
- spaceToWrapAt = str.indexOf(' ', wrapLength + offset);
- if (spaceToWrapAt >= 0) {
- wrappedLine
- .append(str.substring(offset, spaceToWrapAt));
- wrappedLine.append(newLineStr);
- offset = spaceToWrapAt + 1;
- } else {
- wrappedLine.append(str.substring(offset));
- offset = inputLineLength;
- }
- }
- }
- }
- // Whatever is left in line is short enough to just pass through
- wrappedLine.append(str.substring(offset));
- return wrappedLine.toString();
- }
- public static String wrap(final String str, final int wrapLength) {
- return wrap(str, wrapLength, null, false);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement