Java String Split by Line splitLines(final String string)

Here you can find the source of splitLines(final String string)

Description

Splits the given string in a list where each element is a line.

License

Common Public License

Parameter

Parameter Description
string string to be splitted.

Return

list of strings where each string is a line.

Declaration

public static List<String> splitLines(final String string) 

Method Source Code


//package com.java2s;
/*//w  ww.  j av  a2  s  .c om
 * @author Fabio Zadrozny
 * Created: June 2005
 * License: Common Public License v1.0
 */

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

public class Main {
    /**
     * Splits the given string in a list where each element is a line.
     *
     * @param string
     *            string to be splitted.
     * @return list of strings where each string is a line.
     *
     * @note the new line characters are also added to the returned string.
     */
    public static List<String> splitLines(final String string) {
        final List<String> ret = new ArrayList<>();
        final int len = string.length();

        char c;
        final StringBuilder buf = new StringBuilder();

        for (int i = 0; i < len; i++) {
            c = string.charAt(i);
            buf.append(c);
            if (c == '\r') {
                if (i < len - 1 && string.charAt(i + 1) == '\n') {
                    i++;
                    buf.append('\n');
                }
                ret.add(buf.toString());
                buf.setLength(0);
            }
            if (c == '\n') {
                ret.add(buf.toString());
                buf.setLength(0);
            }
        }
        if (buf.length() != 0) {
            ret.add(buf.toString());
        }
        return ret;
    }
}

Related

  1. splitIntoNonEmptyLinesWithoutNetLogoComments( String s)
  2. splitLine(final String line, final char delimiter, final char qualifier, final int initialSize)
  3. splitLine(String input, int splitPosition)
  4. SplitLine(String p_line, String p_delimiter)
  5. splitLines(final String helpMessage)
  6. splitLines(String raw, int limit)
  7. splitLines(String S)
  8. splitLines(String s)
  9. splitLines(String self)