Remove end of line characters from Java string
Asked Answered
A

12

69

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?

Actor answered 27/2, 2009 at 6:5 Comment(1)
StringUtils.chomp()Webbing
E
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", "");
Enyedy answered 27/2, 2009 at 6:13 Comment(4)
I would recommend you used System.getProperty("line.separator");, instead of hardcoded line breakers. Each OS has its own line separator.Pavlish
@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.Cultivate
How would you use the value returned for line.separator? I tried passing "\\" + lineSeparator in the regex and it did not workIlium
otherwise I think str = srt.trim() would also works fineDx
G
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.

Groome answered 12/11, 2013 at 14:11 Comment(0)
F
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.

Federal answered 27/2, 2009 at 6:23 Comment(0)
G
5

Given a String str:

str = str.replaceAll("\\\\r","")
str = str.replaceAll("\\\\n","")
Geniegenii answered 27/2, 2009 at 6:9 Comment(1)
This is an unnecessarily inefficient way to do it.Federal
R
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, "");
Rasia answered 25/10, 2018 at 7:59 Comment(0)
Y
2

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

Yearbook answered 27/2, 2009 at 6:10 Comment(0)
B
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.

Bleach answered 20/9, 2010 at 9:28 Comment(0)
C
1

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

str = "hello\r\njava\r\nbook";
StringEscapeUtils.unescapeJava(str);
Chafee answered 4/1, 2019 at 7:22 Comment(1)
This is deprecatedInvective
S
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.

Scurrilous answered 14/3, 2022 at 21:34 Comment(0)
B
0

Hey we can also use this regex solution.

String chomp = StringUtils.normalizeSpace(sentence.replaceAll("[\\r\\n]"," "));
Burning answered 9/3, 2020 at 19:23 Comment(0)
U
-2

Try below code. It worked for me.

str = str.replaceAll("\\r", "");
str = str.replaceAll("\\n", "");
Unhealthy answered 1/7, 2021 at 11:5 Comment(1)
#594171Prewar
D
-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.

Delisle answered 23/8, 2012 at 5:39 Comment(2)
What is the problem here? Trim takes away everything and gives back just the string?Delisle
Trim removes leading/trailing whitespace. Line breaks in the middle of a string will not be removed.Coryden

© 2022 - 2024 — McMap. All rights reserved.