Java Scanner Usage getLines(String str)

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

Description

Returns all lines from the given string, i.e.

License

Open Source License

Declaration

public static List<String> getLines(String str) 

Method Source Code

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

import java.util.ArrayList;

import java.util.List;

import java.util.Scanner;

public class Main {
    /**//from w w  w  .ja v  a 2 s.  c  om
     * Returns all lines from the given string, i.e. the text between newline characters and start and end of the string. 
     * Also parses empty lines as new lines, e.g. the String "\n\n" yields three empty lines.
     */
    public static List<String> getLines(String str) {
        String line = null;
        List<String> lines = new ArrayList<>();
        if (str.isEmpty()) {
            lines.add("");
            return lines;
        }

        //      if (str.startsWith("\n") || str.startsWith("\r\n"))
        //         lines.add("");

        Scanner scanner = new Scanner(str);
        while (scanner.hasNextLine()) {
            line = scanner.nextLine();
            lines.add(line);
        }
        scanner.close();

        if (str.endsWith("\n") || str.endsWith("\r\n"))
            lines.add("");

        return lines;
    }
}

Related

  1. getFirstInt(String s)
  2. getInput(Scanner in, String message, boolean allowNull)
  3. getInt()
  4. getInt(Scanner sc)
  5. getInteger(String parameter)
  6. getLineStartingWith(Scanner scanner, String starts)
  7. getLngIn()
  8. getNextInput(Scanner scan)
  9. getNextLine(final Scanner scanner)