68

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?

Neuron
  • 5,141
  • 5
  • 38
  • 59

12 Answers12

142

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", "");
TofuBeer
  • 60,850
  • 18
  • 118
  • 163
  • 8
    I would recommend you used `System.getProperty("line.separator");`, instead of hardcoded line breakers. Each OS has its own line separator. – Georgian Aug 12 '13 at 06:39
  • 9
    @GGrec sometimes the text String / File was not made by the same OS. So `System.getProperty("line.separator");` won't work in these cases. But yes, if you can trust the same-OS origin, it is better to use the system property. – Mindwin Remember Monica Feb 02 '15 at 18:24
  • How would you use the value returned for `line.separator`? I tried passing `"\\" + lineSeparator` in the regex and it did not work – Don Cheadle May 28 '15 at 21:11
  • otherwise I think str = srt.trim() would also works fine – Alexis Brunet Jan 21 '21 at 09:58
19
public static void main(final String[] argv) 
{
    String str;

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

It would be useful to add the tabulation in regex too.

ronicst
  • 191
  • 1
  • 2
18

If you want to avoid the regex, or must target an earlier JVM, String.replace() will do:

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

And to remove a CRLF pair:

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

The latter is more efficient than building a regex to do the same thing. But I think the former will be faster as a regex since the string is only parsed once.

Lawrence Dol
  • 63,018
  • 25
  • 139
  • 189
5

Given a String str:

str = str.replaceAll("\\\\r","")
str = str.replaceAll("\\\\n","")
Beep beep
  • 18,873
  • 12
  • 63
  • 78
3

You can either directly pass line terminator e.g. \n, if you know the line terminator in Windows, Mac or UNIX. Alternatively you can use following code to replace line breaks in either of three major operating system.

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

Above code line will replace line breaks with space in Mac, Windows and Linux. Also you can use line-separator. It will work for all OS. Below is the code snippet for line-separator.

String lineSeparator=System.lineSeparator();
String newString=yourString.replace(lineSeparator, "");
Naved Ali
  • 616
  • 1
  • 14
  • 31
2
static byte[] discardWhitespace(byte[] data) {
    byte groomedData[] = new byte[data.length];
    int bytesCopied = 0;

    for (int i = 0; i < data.length; i++) {
        switch (data[i]) {
            case (byte) '\n' :
            case (byte) '\r' :
                break;
            default:
                groomedData[bytesCopied++] = data[i];
        }
    }

    byte packedData[] = new byte[bytesCopied];

    System.arraycopy(groomedData, 0, packedData, 0, bytesCopied);

    return packedData;
}

Code found on commons-codec project.

RazvanM
  • 21
  • 1
2

Have you tried using the replaceAll method to replace any occurence of \n or \r with the empty String?

Rob Lachlan
  • 14,289
  • 5
  • 49
  • 99
1

You can use unescapeJava from org.apache.commons.text.StringEscapeUtils like below

str = "hello\r\njava\r\nbook";
StringEscapeUtils.unescapeJava(str);
Srinivasan Sekar
  • 2,049
  • 13
  • 22
1

I went with \\s+ and it removed \r and \n chars for me.

\s+ will match one or more whitespace characters

final String stringWithWhitespaceChars = "Bart\n\r";
final String stringWithoutEscapeChars = stringWithEscapeChars.replaceAll("\\s+","");

Refer to Regex expressions in Java, \\s vs. \\s+ for in detail informations.

BartusZak
  • 1,041
  • 14
  • 21
0

Hey we can also use this regex solution.

String chomp = StringUtils.normalizeSpace(sentence.replaceAll("[\\r\\n]"," "));
Abhishek Sengupta
  • 2,938
  • 1
  • 28
  • 35
-1

Try below code. It worked for me.

str = str.replaceAll("\\r", "");
str = str.replaceAll("\\n", "");
Nikhil
  • 861
  • 11
  • 15
  • https://stackoverflow.com/questions/593671/remove-end-of-line-characters-from-java-string/68209032#comment405530_593681 – Eric Aya Jul 01 '21 at 11:49
-7

Did you try

string.trim(); 

This is meant to trim all leading and leaning while spaces in the string. Hope this helps.

Edit: (I was not explicit enough)

So, when you string.split(), you will have a string[] - for each of the strings in the array, do a string.trim() and then append it.

String[] tokens = yourString.split(" ");
StringBuffer buff = new StringBuffer();
for (String token : tokens)
{
  buff.append(token.trim());
}

Use stringBuffer/Builder instead of appending in the same string.