Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How split "\n" from user input?

Tags:

java

string

split

Can anyone tell me why this is working well:

String wanttosplit = "asdf...23\n..asd12";
String[] i = wanttosplit.split("\n");
output are:
i[0] = asdf...23
i[1] = ..asd12

When i want to get the data from user like:

import java.util.Scanner;
Scanner scan = new Scanner(System.in);
String wanttosplit = scan.next(); //user enter asdf...23\n..asd12 on the       keyboard
String[] i = wanttosplit.split("\n");
output are:
i[0] = asdf...23\n..asd12

Why it didnt split like in first example?

like image 770
Kuba Avatar asked Oct 12 '17 10:10

Kuba


1 Answers

The difference is that \n in the String literal "asdf...23\n..asd12" is processed by Java compiler, while user input asdf...23\n..asd12 is passed to Scanner as-is.

Java compiler replaces an escape sequence \n with line feed (LF) character, which corresponds to code point 10 in UNICODE. Scanner, on the other hand, passes you two separate characters, '\' and 'n', so when you pass the string to split method, it does not find LF code point separator.

You need to process escape sequence \n yourself, for example, by passing split a regex that recognizes it:

String[] i = wanttosplit.split("(?<!\\\\)\\\\n");

Demo.

like image 182
Sergey Kalinichenko Avatar answered Oct 18 '22 02:10

Sergey Kalinichenko