How to separate "\ n" from user input?

Can someone tell me why this works 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 receive data from a user, for example:

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 is it not divided, as in the first example?

+4
source share
4 answers

The difference is that \nin the Stringliteral "asdf...23\n..asd12"is handled by the Java compiler, a user input asdf...23\n..asd12is passed to Scannerit is.

Java escape- \n (LF), 10 UNICODE. Scanner, , : '\' 'n', , split, LF.

escape- \n , , split , :

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

+6

, , , n, , wanttosplit.split(), , .

wanttosplit ( java '\n' , .

0

aat \n, \\n, Java \n . , \ infront \n, java \n

0

, "\" "n" ? .

, ()

, next() .

0

Source: https://habr.com/ru/post/1687364/


All Articles