Here you can find the source of getTextAsFormattedLines(String text, int lineLength)
Parameter | Description |
---|---|
text | The text to format. |
lineLength | The line length to format the text to. |
public static String getTextAsFormattedLines(String text, int lineLength)
//package com.java2s; /*//from www.j a v a2 s . c o m * Copyright 2006 - Gary Bentley * * 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.List; import java.util.ArrayList; public class Main { /** * Given a chunk of text format it so that you return a new String * with the line length equal to that passed in. * * @param text The text to format. * @param lineLength The line length to format the text to. * @return The formatted text. */ public static String getTextAsFormattedLines(String text, int lineLength) { StringBuffer retdata = new StringBuffer(); List lines = new ArrayList(); String t = new String(text); while (t.length() > lineLength) { // Chop up the description into lines close to lineLength... // Chop off the first lineLength characters... String s = t.substring(0, lineLength); String rest = t.substring(lineLength); // Find the last instance of " ". int lastInd = s.lastIndexOf(' '); // See if the last index if (lineLength - 1), if so then // we have a clean break... if (lastInd == (lineLength)) { retdata.append(s); retdata.append('\n'); } else { // The last index is less so now // we need to check the rest to see // if that starts with a char other // than " ", if so it's part of the // previous word... if (rest.charAt(0) != ' ') { // It is! // Now get the rest of the word and append it // to s... int indexOfFirst = rest.indexOf(' '); String halfWord = rest.substring(0, indexOfFirst); // Substring... s = s + halfWord; // Add s to the list of lines. retdata.append(s); retdata.append('\n'); rest = rest.substring(indexOfFirst + 1); } rest = rest.trim(); } t = rest; } lines.add(t.trim()); retdata.append(t.trim()); retdata.append('\n'); return retdata.toString(); } }