abhishek92
abhishek92

Reputation: 111

How to Split string in java using "\n"

I am taking a command line input string like this:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
     String line = br.readLine();

I want to split this string which is:

String line = "int t; //variable t  
t->a = 0; //t->a does something  
return 0;"

like this:

String[] arr = line.split("\n");  
arr[0] = "int t; //variable t";  
arr[1] = "t->a=0; //t->a does something";  
arr[2] = "return 0";  

but when i run my java program that split function only returns this:

arr[0] = "int t; //variable t";

it didn't returns other two strings that i mentioned above,why this is happening please explain.

Upvotes: 1

Views: 480

Answers (3)

Christian Tapia
Christian Tapia

Reputation: 34176

The method readLine() will read the input until a new-line character is entered. That new-line character is "\n". Therefore, it won't ever read the String separated by "\n".

One solution:

You can read the lines with a while loop and store them in an ArrayList:

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    List<String> lines = new ArrayList<String>();
    String line;

    while ((line = br.readLine()) != null) {
        lines.add(line);
    }

    for (String s : lines) {
        System.out.println(s);
    }

To stop the while you will have to press Ctrl + z (or Ctrl + d in UNIX, if I'm not wrong).

Upvotes: 5

Anirudha
Anirudha

Reputation: 32817

This should work!Also make sure if your input contains \n

 String[] arr = line.split("\r?\n")

Upvotes: 0

sanbhat
sanbhat

Reputation: 17622

From your comment you seem to take the input like this

   BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
    try {
        String line = br.readLine();
        System.out.println(line);
    } catch (IOException e) {
        e.printStackTrace();
    } 

Here the line represents already split string by \n. When you hit enter on the console, the text entered in one line gets captured into line. As per me you are reading line, only once which captures just int t;//variable t, where there is nothing to split.

Upvotes: 0

Related Questions