Here you can find the source of wrapText(String inString, String newline, int wrapColumn)
Parameter | Description |
---|---|
inString | Text which is in need of word-wrapping. |
newline | The characters that define a newline. |
wrapColumn | The column to wrap the words at. |
This method wraps long lines based on the supplied wrapColumn parameter. Note: Remove or expand tabs before calling this method.
public static String wrapText(String inString, String newline, int wrapColumn)
//package com.java2s; /* Please see the license information at the end of this file. */ import java.util.*; public class Main { /** Lines wraps a block of text. */*from w w w.ja va2 s. co m*/ * @param inString Text which is in need of word-wrapping. * * @param newline The characters that define a newline. * * @param wrapColumn The column to wrap the words at. * * @return The text with all the long lines word-wrapped. * * <p> * This method wraps long lines based on the supplied wrapColumn parameter. * Note: Remove or expand tabs before calling this method. * </p> */ public static String wrapText(String inString, String newline, int wrapColumn) { StringTokenizer lineTokenizer = new StringTokenizer(inString, newline, true); StringBuffer stringBuffer = new StringBuffer(); while (lineTokenizer.hasMoreTokens()) { try { String nextLine = lineTokenizer.nextToken(); if (nextLine.length() > wrapColumn) { // Line is long enough to be wrapped. nextLine = wrapLine(nextLine, newline, wrapColumn); } stringBuffer.append(nextLine); } catch (NoSuchElementException e) { break; } } return (stringBuffer.toString()); } /** Wrap one line of text. * * @param line A line which is in need of word-wrapping. * * @param newline The characters that define a newline. * * @param wrapColumn The column to wrap the words at. * * @return A line with newlines inserted. */ public static String wrapLine(String line, String newline, int wrapColumn) { StringBuffer wrappedLine = new StringBuffer(); while (line.length() > wrapColumn) { int spaceToWrapAt = line.lastIndexOf(' ', wrapColumn); if (spaceToWrapAt >= 0) { wrappedLine.append(line.substring(0, spaceToWrapAt)); wrappedLine.append(newline); line = line.substring(spaceToWrapAt + 1); } // This must be a really long word or URL. Pass it // through unchanged even though it's longer than the // wrapColumn would allow. This behavior could be // dependent on a parameter for those situations when // someone wants long words broken at line length. else { spaceToWrapAt = line.indexOf(' ', wrapColumn); if (spaceToWrapAt >= 0) { wrappedLine.append(line.substring(0, spaceToWrapAt)); wrappedLine.append(newline); line = line.substring(spaceToWrapAt + 1); } else { wrappedLine.append(line); line = ""; } } } // Remaining text in line is shorter than wrap column. wrappedLine.append(line); return (wrappedLine.toString()); } }