Replace '\n' by ',' in java

Ramya Selvarani picture Ramya Selvarani · Mar 3, 2017 · Viewed 29.5k times · Source

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.

Answer

anacron picture anacron · Mar 3, 2017

\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(),","));