Java String Wrap wrapString(String str)

Here you can find the source of wrapString(String str)

Description

wrap String

License

Apache License

Declaration

public static String wrapString(String str) 

Method Source Code


//package com.java2s;
/*// w  w w . j av a 2s . c om
 * Copyright 2013 Serdar.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Main {
    private static final short MAX_LENGTH = 90;

    public static String wrapString(String str) {
        return wrapString(str, MAX_LENGTH);
    }

    public static String wrapString(String str, int maxWidth) {
        List<String> wrap = wrap(str, maxWidth);
        StringBuilder stringBuilder = new StringBuilder();
        for (String line : wrap) {
            stringBuilder.append(line).append("\n");
        }
        return stringBuilder.toString();
    }

    /**
     * Returns an array of strings, one for each line in the string after it has
     * been wrapped to fit lines of <var>maxWidth</var>. Lines end with any of
     * cr, lf, or cr lf. A line ending at the end of the string will not output
     * a further, empty string.
     * <p>
     * This code assumes <var>str</var> is not <code>null</code>.
     *
     * @param str the string to split
     * @param maxWidth the max line width, in points
     * @return a non-empty list of strings
     */
    public static List<String> wrap(String str, int maxWidth) {
        List<String> lines = splitIntoLines(str);
        if (lines.isEmpty()) {
            return lines;
        }

        ArrayList<String> strings = new ArrayList<String>();
        for (Iterator<String> iter = lines.iterator(); iter.hasNext();) {
            wrapLineInto(iter.next(), strings, maxWidth);
        }
        return strings;
    }

    /**
     * Returns an array of strings, one for each line in the string. Lines end
     * with any of cr, lf, or cr lf. A line ending at the end of the string will
     * not output a further, empty string.
     * <p>
     * This code assumes <var>str</var> is not <code>null</code>.
     *
     * @param str the string to split
     * @return a non-empty list of strings
     */
    public static List<String> splitIntoLines(String str) {
        ArrayList<String> strings = new ArrayList<String>();
        if (str != null) {
            int len = str.length();
            if (len == 0) {
                strings.add("");
                return strings;
            }

            int lineStart = 0;

            for (int i = 0; i < len; ++i) {
                char c = str.charAt(i);
                if (c == '\r') {
                    int newlineLength = 1;
                    if ((i + 1) < len && str.charAt(i + 1) == '\n') {
                        newlineLength = 2;
                    }
                    strings.add(str.substring(lineStart, i));
                    lineStart = i + newlineLength;
                    if (newlineLength == 2) // skip \n next time through loop
                    {
                        ++i;
                    }
                } else if (c == '\n') {
                    strings.add(str.substring(lineStart, i));
                    lineStart = i + 1;
                }
            }
            if (lineStart < len) {
                strings.add(str.substring(lineStart));
            }
        }
        return strings;
    }

    /**
     * Given a line of text and font metrics information, wrap the line and add
     * the new line(s) to <var>list</var>.
     *
     * @param line a line of text
     * @param list an output list of strings
     * @param fm font metrics
     * @param maxWidth maximum width of the line(s)
     */
    public static void wrapLineInto(String line, List<String> list, int maxWidth) {
        int len = line.length();
        while (len > maxWidth) {
            // Guess where to split the line. Look for the next space before
            // or after the guess.
            int pos;
            if (len > maxWidth) // Too long
            {
                pos = findBreakBefore(line, maxWidth);
            } else { // Too short or possibly just right
                pos = len;
            }
            list.add(line.substring(0, pos).trim());
            line = line.substring(pos).trim();
            len = line.length();
        }
        if (len > 0) {
            list.add(line);
        }
    }

    /**
     * Returns the index of the first whitespace character or '-' in
     * <var>line</var>
     * that is at or before <var>start</var>. Returns -1 if no such character is
     * found.
     *
     * @param line a string
     * @param start where to star looking
     */
    public static int findBreakBefore(String line, int start) {
        for (int i = start; i >= 0; --i) {
            char c = line.charAt(i);
            if (Character.isWhitespace(c) || c == '-') {
                return i;
            }
        }
        return -1;
    }
}

Related

  1. getWrappedLine(String line, int lineLength)
  2. lineWrap(String text, int width, boolean shiftNewLines)
  3. wordWrap(final String rawString, final int lineLength)
  4. wordWrap(String entry)
  5. wordWrap(String input, int width)
  6. wrapString(String text, int maxLength)
  7. wrapText(String description)
  8. wrapText(String inString, String newline, int wrapColumn)
  9. wrapText(String line, int maxLineLength)