Java String Split by Length getSplitLines(String input, int maxLineLength)

Here you can find the source of getSplitLines(String input, int maxLineLength)

Description

get Split Lines

License

Open Source License

Declaration

public static String[] getSplitLines(String input, int maxLineLength) 

Method Source Code

//package com.java2s;
/*//from   w  ww.  ja  v a  2  s . c  om
 * PS3 Media Server, for streaming any medias to your PS3.
 * Copyright (C) 2012  Ph.Waeber
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; version 2
 * of the License only.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

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

public class Main {
    public static String[] getSplitLines(String input, int maxLineLength) {
        List<String> lines = new ArrayList<String>();
        if (maxLineLength > 0 && input.length() > maxLineLength) {
            int cutPos;
            do {
                cutPos = getCutOffPosition(input, maxLineLength);
                String text;
                if (cutPos > 0) {
                    text = input.substring(0, cutPos).trim();
                    input = input.substring(cutPos).trim();
                } else {
                    text = input.trim();
                    input = "";
                }

                lines.add(text);

            } while (cutPos > 0);
        } else {
            lines.add(input);
        }
        return lines.toArray(new String[lines.size()]);
    }

    private static int getCutOffPosition(String convertedMask,
            int maxLineLength) {
        int cutOffPos = -1;
        if (maxLineLength > 0 && convertedMask.length() > maxLineLength) {
            cutOffPos = maxLineLength;
            while (cutOffPos > 0 && convertedMask.charAt(cutOffPos) != ' ') {
                cutOffPos--;
            }
            if (cutOffPos == 0) {
                cutOffPos = maxLineLength;
            }
        }
        return cutOffPos;
    }
}

Related

  1. lineSplit(String text, int len)
  2. split(final String value, final int maxLength)
  3. split(String message, int maxPages, int pageSize)
  4. splitArray(byte[] array, int len)