Java String Split by Line splitIntoLines(String str)

Here you can find the source of splitIntoLines(String str)

Description

Returns an array of strings, one for each line in the string.

License

Apache License

Parameter

Parameter Description
str the string to split

Return

a non-empty list of strings

Declaration

public static List splitIntoLines(String str) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.util.ArrayList;

import java.util.List;

public class Main {
    /**//  w ww .  java 2s  .c  om
     * Returns an array of strings, one for each line in the string. Lines end
     * with any of cr, lf, or cr lf. A line ending at the end of the string will
     * not output a further, empty string.
     * <p>
     * This code assumes <var>str</var> is not <code>null</code>.
     * 
     * @param str
     *          the string to split
     * @return a non-empty list of strings
     */
    public static List splitIntoLines(String str) {
        ArrayList strings = new ArrayList();

        int len = str.length();
        if (len == 0) {
            strings.add("");
            return strings;
        }

        int lineStart = 0;

        for (int i = 0; i < len; ++i) {
            char c = str.charAt(i);
            if (c == '\r') {
                int newlineLength = 1;
                if ((i + 1) < len && str.charAt(i + 1) == '\n')
                    newlineLength = 2;
                strings.add(str.substring(lineStart, i));
                lineStart = i + newlineLength;
                if (newlineLength == 2) // skip \n next time through loop
                    ++i;
            } else if (c == '\n') {
                strings.add(str.substring(lineStart, i));
                lineStart = i + 1;
            }
        }
        if (lineStart < len)
            strings.add(str.substring(lineStart));

        return strings;
    }
}

Related

  1. splitBySeparatorQuoteAndParen(String line, char sep)
  2. splitCommandLine(String str, boolean extract)
  3. splitCommaSeparated(String line)
  4. splitHiddenNewLine(String s)
  5. splitInt(String line, String seperator, int def)
  6. splitIntoNonEmptyLines(String s)
  7. splitIntoNonEmptyLinesWithoutNetLogoComments( String s)
  8. splitLine(final String line, final char delimiter, final char qualifier, final int initialSize)
  9. splitLine(String input, int splitPosition)