There is a string 1 1 1 1 1 1\n2 2 2 2 2 2\n3 3 3 3 3 3\n4 4 4 4 4 4 . If we apply split("\n") to it split("\n") then we get an array of strings divided by \n . However, if we ask the user to enter this line from the console and also apply split("\n") to this line, the line will not be split. Why is that?

  • And how do you read from the console? Sure that the line there is exactly what happens? - Vartlok
  • Sure, I tried debager many times. I read so Scanner sc = new Scanner (); String str = new String (sc.nextLine ()); - DmitriI Gubenko
  • Do you enter \n in the console? If so then you will split('\\n') . The console does not provide for a carriage return (simple Read) - nick_n_a
  • Yes, I just type this line or something similar in the console. Or copy and paste it from the clipboard. At the same time split ('\\ n') does not break it. This is how it splits-> split (Pattern.quote ("\\ n")). I just don't understand what I'm doing wrong. - DmitriI Gubenko

1 answer 1

Because the user cannot enter escape sequences with direct text. It is only in literals that you can write \n or %n and they are interpreted as a line break.

Read the user's input line by line (in a loop) into the collection, until he enters the secret word ( quit , for example).

Well, or if you realize that \n in your case from the user literally enters the line as text, then escape the backslash: split("\\n")

  • I did that. When this happens the same story. Does not break. Splits is to write like this split (Pattern.quote ("\\ n")). But if, honestly, I don’t really understand why just split ("\\ n") does not work. - DmitriI Gubenko
  • @DmitriIGubenko Does not split user input or a string specified by a literal? Either one or the other) - free_ze
  • The literal then breaks =). And the string String obtained from user input is not. I had to apply to regular expressions, although the task seems to be quite elementary and everything should work without them and so) - DmitriI Gubenko
  • @DmitriIGubenko split ("\\ n") breaks the literal with "\ n"? Are you sure?) - free_ze
  • String [] strArr = "1 3 1 2 \ n2 3 2 2 \ n5 6 7 1 \ n3 3 1 0" .split ("\\ n"); Here, here it works. - DmitriI Gubenko