Java String Wrap lineWrap(String text, int width, boolean shiftNewLines)

Here you can find the source of lineWrap(String text, int width, boolean shiftNewLines)

Description

line Wrap

License

Open Source License

Declaration

public static List<String> lineWrap(String text, int width, boolean shiftNewLines) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

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

public class Main {
    public static List<String> lineWrap(String text, int width, boolean shiftNewLines) {
        String[] words = text.trim().split(" ");
        StringBuilder currentLine = new StringBuilder();
        List<String> newLines = new ArrayList<String>();

        int currentLength = 0;
        for (int i = 0; i < words.length; i++) {
            currentLine.append(words[i] + " ");
            currentLength = currentLine.length();

            int nextWordLength = 0;
            if (i + 1 < words.length)
                nextWordLength = words[i + 1].length();
            if (currentLength + nextWordLength >= width - 2 || i + 1 >= words.length) {
                newLines.add(currentLine.toString());
                currentLine = new StringBuilder();
                if (shiftNewLines)
                    currentLine.append(" ");
            }//from  w  w w .  ja  va 2  s  .c om
        }

        return newLines;
    }
}

Related

  1. getWordWrappedText(int maxWidth, String... lines)
  2. getWrappedLine(String line, int lineLength)
  3. wordWrap(final String rawString, final int lineLength)
  4. wordWrap(String entry)
  5. wordWrap(String input, int width)
  6. wrapString(String str)