Remove end of line characters from Java string

sahil picture sahil · Feb 27, 2009 · Viewed 190.5k times · Source

I have string like this

"hello
java
book"

I want remove \r and \n from String(hello\r\njava\r\nbook). I want the result to be "hellojavabook". How can I do this?

Answer

TofuBeer picture TofuBeer · Feb 27, 2009

Regex with replaceAll.

public class Main
{
    public static void main(final String[] argv) 
    {
        String str;

        str = "hello\r\njava\r\nbook";
        str = str.replaceAll("(\\r|\\n)", "");
        System.out.println(str);
    }
}

If you only want to remove \r\n when they are pairs (the above code removes either \r or \n) do this instead:

str = str.replaceAll("\\r\\n", "");