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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With