Here you can find the source of getWrappedLine(String line, int lineLength)
Parameter | Description |
---|---|
line | the line to word-wrap |
lineLength | the maximum length any segment should be. |
public static String getWrappedLine(String line, int lineLength)
//package com.java2s; /*/* w w w. j ava2 s . c om*/ * Copyright (C) 2001-2004 Colin Bell * colbell@users.sourceforge.net * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ import java.util.ArrayList; import java.util.Iterator; public class Main { /** * Inserts newlines at or before lineLength at spaces or commas. If no space * or comma can be found, the resultant line will not be broken up by * newlines. * * @param line the line to word-wrap * @param lineLength the maximum length any segment should be. * @return a line with newlines inserted */ public static String getWrappedLine(String line, int lineLength) { if (line.length() <= lineLength) { return line; } StringBuffer result = new StringBuffer(); char[] lineChars = line.toCharArray(); int lastBreakCharIdx = -1; ArrayList<Integer> breakPoints = new ArrayList<Integer>(); // look for places to break the string for (int i = 0; i < lineChars.length; i++) { char curr = lineChars[i]; if (curr == ' ' || curr == ',') { lastBreakCharIdx = i; } if (i > 0 && (i % lineLength == 0) && lastBreakCharIdx != -1) { breakPoints.add(Integer.valueOf(lastBreakCharIdx)); } } if (lastBreakCharIdx != lineChars.length) { breakPoints.add(Integer.valueOf(lineChars.length)); } int lastBreakPointIdx = 0; for (Iterator<Integer> iter = breakPoints.iterator(); iter.hasNext();) { int breakPointIdx = (iter.next()).intValue() + 1; if (breakPointIdx > line.length()) { breakPointIdx = line.length(); } String part = line.substring(lastBreakPointIdx, breakPointIdx); result.append(part.trim()); if (!part.trim().endsWith("\\n")) { result.append("\n"); } lastBreakPointIdx = breakPointIdx; } return result.toString(); } }