Java - Write code to Return an ArrayList of strings, one for each line in the string. This code assumes str is not null.

Requirements

Write code to Return an ArrayList of strings, one for each line in the string. This code assumes str is not null.

Demo

//package com.book2s;

import java.util.*;

public class Main {
    public static void main(String[] argv) {
        String str = "boo\n\n\n\nk2\r\r\r\ns.com";
        System.out.println(splitIntoLines(str));
    }//from w w w.  j  ava2 s  .c o  m

    /**
     * Returns an ArrayList of strings, one for each line in the string.<br><br>
     * 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<String> splitIntoLines(String str) {
        ArrayList<String> strings = new ArrayList<String>();

        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 Exercise