Friday, April 8, 2011

Remove end of line characters from Java string

I have string like this

"hello
java
book"

I want remove \r and \n from string(hello\r\njava\r\nbook). I want string as "hellojavabook". How can i do this?

From stackoverflow
  • Given a String str:

    str = str.replaceAll("\\\\r","")
    str = str.replaceAll("\\\\n","")
    
    Rob Lachlan : Zounds. Beat me to it!
    Software Monkey : This is an unnecessarily inefficient way to do it.
  • Have you tried using the replaceAll method to replace any occurence of \n or \r with the empty String?

  • str = "hello java book" str.replaceAll("\r", "") str.replaceAll("\n", "")

    Not that I know java or anything, but I got the info from Google in less than 2 seconds.

    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html#replaceAll(java.lang.String,%20java.lang.String)

    wds : Which is why you got the escaping of the \r wrong. :)
  • 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", "");
    
  • 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.

  • 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.

0 comments:

Post a Comment