Java String Chop chopLongLinesAtSpaces(int maxLineLenght, String text)

Here you can find the source of chopLongLinesAtSpaces(int maxLineLenght, String text)

Description

chop Long Lines At Spaces

License

Open Source License

Declaration

public static String chopLongLinesAtSpaces(int maxLineLenght, String text) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2010, 2012 Tasktop Technologies
 * Copyright (c) 2010, 2011 SpringSource, a division of VMware
 * /*from w ww.j a  va2s .c  o  m*/
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors:
 *     Tasktop Technologies - initial API and implementation
 ******************************************************************************/

public class Main {
    public static String chopLongLinesAtSpaces(int maxLineLenght, String text) {
        StringBuilder result = new StringBuilder();

        int currentIndex = 0;

        while (currentIndex < text.length()) {
            int newLineIdx = text.indexOf("\n", currentIndex);
            String line;

            // Get the next line
            if (newLineIdx == -1) {
                line = text.substring(currentIndex);
                currentIndex = text.length();
            } else {
                line = text.substring(currentIndex, newLineIdx + 1);
                currentIndex = newLineIdx + 1;
            }

            // Chop it up
            while (shouldChop(maxLineLenght, line)) {
                int spaceIdx = line.substring(0, maxLineLenght).lastIndexOf(" ");
                if (spaceIdx != -1) {
                    result.append(line.substring(0, spaceIdx)).append("\n");
                    line = line.substring(spaceIdx + 1);
                } else {
                    result.append(line.substring(0, maxLineLenght)).append("\n");
                    line = line.substring(maxLineLenght);
                }

            }
            result.append(line);

        }

        return result.toString();
    }

    private static boolean shouldChop(int maxLineLenght, String line) {
        return line.length() > maxLineLenght && !(line.length() == maxLineLenght + 1 && line.endsWith("\n"));
    }
}

Related

  1. chopFractionalPart(float original, int no_of_digits )
  2. chopId(String name)
  3. chopIfMatch(StringBuilder sb, char ch)
  4. chopLast(String value, int chars)
  5. chopLenghtyString(String title, int maxLen)
  6. chopNull(String str)
  7. chopPrefix(String x, String prefix)
  8. ChopRt(String this_string, String chomp_off)
  9. chopScheme(String path)