Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace '\n' by ',' in java

I want to take input from user as String and replace the newline character \n with ,

I tried :

String test ="s1\ns2\ns3\ns4"; System.out.println(test.replaceAll("\n",","));

Output was s1,s2,s3,s4

But when I try the same code by getting input from UI it's not working.

When I debug it the string test(which I hardcoded) is treated as,

s1

s2

s3

s4

but the string from UI is "s1\ns2\ns3\ns4".

Please suggest what is wrong.

like image 835
Ramya Selvarani Avatar asked Mar 03 '17 07:03

Ramya Selvarani


1 Answers

\n is the new line character. If you need to replace that actual backslash character followed by n, Then you need to use this:

String test ="s1\ns2\ns3\ns4";
System.out.println(test.replaceAll("\\n",","));

Update:

You can use the System.lineSeparator(); instead of the \n character.

System.out.println(test.replaceAll(System.lineSeparator(),","));
like image 100
anacron Avatar answered Nov 03 '22 05:11

anacron