简体   繁体   中英

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.

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).

这应该可行!还要确保您的输入内容是否包含\\n

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM