Removing a hard Enter from a String

75 Views Asked by At

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);
2

There are 2 best solutions below

0
g00se On BEST ANSWER

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","");
1
krishnan On

Unless you don't have a specific reason to use java-7 today, Here's a solution using java 13 or above

    String in= """
                strengthened columns 
                with GRPES
                """;
    in = in.replaceAll("\\n","");
    System.out.println(in);

I have observed the question is tagged with java-7, do let me know if you are looking for a solution specific to the version