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?
|
1 answer
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
|
\nin the console? If so then you willsplit('\\n'). The console does not provide for a carriage return (simple Read) - nick_n_a