Java String Split by Length lineSplit(String text, int len)

Here you can find the source of lineSplit(String text, int len)

Description

Splits a string on word boundries.

License

Open Source License

Parameter

Parameter Description
text a parameter
len a parameter

Declaration

public static List<String> lineSplit(String text, int len) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

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

public class Main {
    /**//  w w  w . ja v a 2 s  .c  om
     * Splits a string on word boundries.
     * @param text
     * @param len
     * @return 
     */
    public static List<String> lineSplit(String text, int len) {
        // return empty array for null text
        if (text == null) {
            return new ArrayList<>();
        }

        // return text if len is zero or less
        // or text is less than length
        if (len <= 0 || text.length() <= len) {
            return new ArrayList<>(Arrays.asList(new String[] { text }));
        }

        char[] chars = text.toCharArray();
        List<String> lines = new ArrayList<>();
        StringBuilder line = new StringBuilder();
        StringBuilder word = new StringBuilder();

        for (int i = 0; i < chars.length; i++) {
            word.append(chars[i]);

            if (chars[i] == ' ') {
                if ((line.length() + word.length()) > len) {
                    lines.add(line.toString());
                    line.delete(0, line.length());
                }

                line.append(word);
                word.delete(0, word.length());
            }
        }

        // handle any extra chars in current word
        if (word.length() > 0) {
            if ((line.length() + word.length()) > len) {
                lines.add(line.toString());
                line.delete(0, line.length());
            }
            line.append(word);
        }

        // handle extra line
        if (line.length() > 0) {
            lines.add(line.toString());
        }

        return lines;
    }
}

Related

  1. getSplitLines(String input, int maxLineLength)
  2. split(final String value, final int maxLength)
  3. split(String message, int maxPages, int pageSize)
  4. splitArray(byte[] array, int len)
  5. splitByLength(String string, int len)