Java Word Wrap wrapString(String original, int width, BreakIterator breakIterator, boolean removeNewLines)

Here you can find the source of wrapString(String original, int width, BreakIterator breakIterator, boolean removeNewLines)

Description

Wrap multi-line strings.

License

Sun Public License Notice

Parameter

Parameter Description
original the original string to wrap
width the maximum width of lines
breakIterator algorithm for breaking lines
removeNewLines if <code>true</code>, any newlines in the original string are ignored

Return

the whole string with embedded newlines

Declaration

public static String wrapString(String original, int width, BreakIterator breakIterator,
        boolean removeNewLines) 

Method Source Code

//package com.java2s;
/*//w  ww  .  jav  a2  s .  c  om
 *                 Sun Public License Notice
 *
 * The contents of this file are subject to the Sun Public License
 * Version 1.0 (the "License"). You may not use this file except in
 * compliance with the License. A copy of the License is available at
 * http://www.sun.com/
 *
 * The Original Code is NetBeans. The Initial Developer of the Original
 * Code is Sun Microsystems, Inc. Portions Copyright 1997-2004 Sun
 * Microsystems, Inc. All Rights Reserved.
 */

import java.util.*;

import java.text.BreakIterator;

public class Main {
    /** Wrap multi-line strings.
    * @param original  the original string to wrap
    * @param width     the maximum width of lines
    * @param breakIterator algorithm for breaking lines
    * @param removeNewLines if <code>true</code>, any newlines in the original string are ignored
    * @return the whole string with embedded newlines
    */
    public static String wrapString(String original, int width, BreakIterator breakIterator,
            boolean removeNewLines) {

        String[] sarray = wrapStringToArray(original, width, breakIterator, removeNewLines);
        StringBuffer retBuf = new StringBuffer();

        for (int i = 0; i < sarray.length; i++) {
            retBuf.append(sarray[i]);
            retBuf.append('\n');
        }
        return retBuf.toString();
    }

    /** Wrap multi-line strings.
    * @param original  the original string to wrap
    * @param width     the maximum width of lines
    * @param wrapWords if <code>true</code>, the lines are wrapped on word boundaries (if possible);
    *                  if <code>false</code>, character boundaries are used
    * @param removeNewLines if <code>true</code>, any newlines in the original string are ignored
    * @return the whole string with embedded newlines
    * @deprecated Use {@link #wrapString (String, int, BreakIterator, boolean)} as it is friendlier to I18N.
    */
    public static String wrapString(String original, int width, boolean wrapWords, boolean removeNewLines) {
        // substitute original newlines with spaces,
        // remove newlines from head and tail
        if (removeNewLines) {
            while (original.startsWith("\n")) // NOI18N
                original = original.substring(1);
            while (original.endsWith("\n")) // NOI18N
                original = original.substring(0, original.length() - 1);
            original = original.replace('\n', ' ');
        }

        if (width < 1)
            width = 1;
        if (original.length() <= width)
            return original;

        java.util.Vector lines = new java.util.Vector();
        int lineStart = 0; // the position of start of currently processed line in the original string
        int lastSpacePos = -1;
        for (int i = 0; i < original.length(); i++) {
            if (lineStart >= original.length() - 1)
                break;

            // newline in the original string
            if (original.charAt(i) == '\n') {
                lines.addElement(original.substring(lineStart, i));
                lineStart = i + 1;
                lastSpacePos = -1;
                continue;
            }

            // remember last space position
            if (Character.isSpaceChar(original.charAt(i)))
                lastSpacePos = i;

            // last position in the original string
            if (i == original.length() - 1) {
                lines.addElement(original.substring(lineStart));
                break;
            }

            // reached width
            if (i - lineStart == width) {
                if (wrapWords && (lastSpacePos != -1)) {
                    lines.addElement(original.substring(lineStart, lastSpacePos));
                    lineStart = lastSpacePos + 1; // the space is consumed for the newline
                    lastSpacePos = -1;
                } else {
                    lines.addElement(original.substring(lineStart, i));
                    lineStart = i;
                    lastSpacePos = -1;
                }
            }
        }

        StringBuffer retBuf = new StringBuffer();
        for (java.util.Enumeration e = lines.elements(); e.hasMoreElements();) {
            retBuf.append((String) e.nextElement());
            retBuf.append('\n');
        }
        return retBuf.toString();
    }

    /** Wrap multi-line strings (and get the individual lines).
    * @param original  the original string to wrap
    * @param width     the maximum width of lines
    * @param wrapWords if <code>true</code>, the lines are wrapped on word boundaries (if possible);
    *                  if <code>false</code>, character boundaries are used
    * @param removeNewLines if <code>true</code>, any newlines in the original string are ignored
    * @return the lines after wrapping
    * @deprecated use {@link #wrapStringToArray(String, int, BreakIterator, boolean)} since it is better for I18N
    */
    public static String[] wrapStringToArray(String original, int width, boolean wrapWords,
            boolean removeNewLines) {
        BreakIterator bi = (wrapWords ? BreakIterator.getWordInstance() : BreakIterator.getCharacterInstance());
        return wrapStringToArray(original, width, bi, removeNewLines);
    }

    /** Wrap multi-line strings (and get the individual lines).
    * @param original  the original string to wrap
    * @param width     the maximum width of lines
    * @param breakIterator breaks original to chars, words, sentences, depending on what instance you provide.
    * @param removeNewLines if <code>true</code>, any newlines in the original string are ignored
    * @return the lines after wrapping
    */
    public static String[] wrapStringToArray(String original, int width, BreakIterator breakIterator,
            boolean removeNewLines) {

        if (original.length() == 0) {
            return new String[] { original };
        }

        String[] workingSet;

        // substitute original newlines with spaces,
        // remove newlines from head and tail
        if (removeNewLines) {
            original = trimString(original);
            original = original.replace('\n', ' ');
            workingSet = new String[] { original };
        } else {
            StringTokenizer tokens = new StringTokenizer(original, "\n"); // NOI18N
            int len = tokens.countTokens();
            workingSet = new String[len];

            for (int i = 0; i < len; i++) {
                workingSet[i] = tokens.nextToken();
            }
        }

        if (width < 1)
            width = 1;
        if (original.length() <= width) {
            return workingSet;
        }

        widthcheck: {
            boolean ok = true;
            for (int i = 0; i < workingSet.length; i++) {
                ok = ok && (workingSet[i].length() < width);
                if (!ok) {
                    break widthcheck;
                }
            }

            return workingSet;
        }

        java.util.ArrayList lines = new java.util.ArrayList();

        int lineStart = 0; // the position of start of currently processed line in the original string
        for (int i = 0; i < workingSet.length; i++) {
            if (workingSet[i].length() < width) {
                lines.add(workingSet[i]);
            } else {
                breakIterator.setText(workingSet[i]);
                int nextStart = breakIterator.next();
                int prevStart = 0;
                do {
                    while (((nextStart - lineStart) < width) && (nextStart != BreakIterator.DONE)) {
                        prevStart = nextStart;
                        nextStart = breakIterator.next();
                    }

                    if (nextStart == BreakIterator.DONE) {
                        nextStart = prevStart = workingSet[i].length();
                    }

                    if (prevStart == 0) {
                        prevStart = nextStart;
                    }

                    lines.add(workingSet[i].substring(lineStart, prevStart));

                    lineStart = prevStart;
                    prevStart = 0;
                } while (lineStart < workingSet[i].length());

                lineStart = 0;
            }
        }

        String s[] = new String[lines.size()];
        return (String[]) lines.toArray(s);
    }

    /** trims String
    * @param s a String to trim
    * @return trimmed String
    */
    private static String trimString(String s) {
        int idx = 0;
        char c;
        final int slen = s.length();

        if (slen == 0) {
            return s;
        }

        do {
            c = s.charAt(idx++);
        } while ((c == '\n' || c == '\r') && (idx < slen));

        s = s.substring(--idx);
        idx = s.length() - 1;

        if (idx < 0) {
            return s;
        }

        do {
            c = s.charAt(idx--);
        } while ((c == '\n' || c == '\r') && (idx >= 0));

        return s.substring(0, idx + 2);
    }
}

Related

  1. wordWrap(String input, int width, Locale locale)
  2. wordWrap(String input, int width, Locale locale)
  3. wordWrap(String input, int width, Locale locale)
  4. wrapStringToArray(String original, int width, BreakIterator breakIterator, boolean removeNewLines)
  5. wrapText(String s, int width, boolean noIterator)
  6. wrapText(String string, int theWrapLength)