Reputation: 25
This may have been asked before but I haven't come across an answer. I have a string that looks like
" ___________________ \n|_ | ___ _ _|\n| | | _|___|"
which I am passing to a java program as a command line argument. Literally just paste that string as a command line argument.
The first line in my program is
String [] array = args[0].split("\n");
I want to split it on the "\n" but I can't seem to do it with split("\n") or split("\\n"). What am I doing wrong?
Upvotes: 1
Views: 144
Reputation: 11911
If your string is passed in containing literal backslashes you have to match it using split("\\\\n")
.
Explanation: to match a backslash in regex you have to excape it, so the regex is \\n
. To input this through a java String-literal you have to excape each of the two backslashes in the regex, so it becomes "\\\\n"
.
...just don't ask me about matching double backslashes ;-)
Upvotes: 0
Reputation: 8466
\n - New Line Feed
\r - Carriage Return
String input = "___________________ \n|_ | ___ _ _|\n| | | _|___|";
String[] splitValue = input.split("[\\r\\n]+");
Upvotes: 1
Reputation: 2050
String data=" ___________________ \n|_ | ___ _ _|\n| | | _|___|";
String data1[]=data.split("\\n");
System.out.println(data);
Gives output.
___________________
|_ | ___ _ _|
| | | _|___|
Upvotes: 1
Reputation: 5531
try
String str =" ___________________ \n|_ | ___ _ _|\n| | | _|___|";
String[] arr = str.split("\n");
System.out.println(Arrays.deepToString(arr));
Upvotes: 2