4

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?

Kuba
  • 63
  • 1
  • 5

4 Answers4

6

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

In your second example, the string entered by the user contains a backslash followed by the letter n, but the parameter passed to wanttosplit.split() is a single character string containing the newline character.

In the first example wanttosplit contains a newline character (because the java compiler has replaced the pattern '\n' with a single character representing newline.

JimNicholson
  • 351
  • 2
  • 9
0

To split aat the user input \n you need to split at \\n because Java will pick \n as a newline-character. Therefor if you add another \ infront of \n java will escape the newline-character and instead splits at the actual text \n

Dinh
  • 759
  • 5
  • 16
0

Looks like you literally input '\' and 'n' via console? Scanner won't esacpe that sequence and instead take it as is.

When getting input from Scanner you also don't need to split lines, because Scanner always gives you one line when performing next()

If you want to read-in multiple lines from the user you should call next() multiple times.

subject42
  • 51
  • 5