Search code examples
javastringjava-7

Removing a hard Enter from a String


What is the best way to remove a hard enter from a String?

Input:

String in= "strengthened columns 
with GRPES
";

Expected output: strengthened columns with GRPES

I tried the below code, but it's not working for me.

in = in.replaceAll("\\r\\n","");
System.out.println(in);

Solution

  • Actually you don't escape standard escape sequences when you use regexes. Also you don't want to specify an order of escape sequences - you just want to eliminate any type of line separator, so

    in = in.replaceAll("[\r\n]","");
    

    With later versions of Java, that could probably be

    in = in.replaceAll("\\R","");