aspose file tools*
The moose likes Java in General and the fly likes Eliminating new line characters from a string Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Eliminating new line characters from a string" Watch "Eliminating new line characters from a string" New topic
Author

Eliminating new line characters from a string

Barry Brashear
Ranch Hand

Joined: Jun 05, 2001
Posts: 303
I need to write a routine to remove the characters '\r' and '\n' from a
string. Does anyone have a slick way to do this?

Thanks.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38334
    
  23
replaceAll method of String?

myString.replaceAll("\n", "");
Jeff Storey
Ranch Hand

Joined: Oct 09, 2006
Posts: 118
Just to be a little more picky, rather than using "\n", I would use System.getProperty("line.separator"). This gives you the system specific newline character, although in most cases the "\n" would be sufficient.
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 41480
    
  51
Just to be a little more picky, rather than using "\n", I would use System.getProperty("line.separator"). This gives you the system specific newline character, although in most cases the "\n" would be sufficient.[/QB]

To be even more picky, I think that might fail on Windows where the line separator is the \r\n sequence, so it would not get rid of individual \r or \n characters. Using Campbell suggestion twice in a row should work fine.


Ping & DNS - my free Android networking tools app
Alan Moore
Ranch Hand

Joined: May 06, 2004
Posts: 262
It doesn't matter what platform the program is running on, you need to account for all three of the standard line separators: "\n" (Unix/Linux/OSX), "\r\n" (Windows/various internet protocols), and "\r" (older Macs). Fortunately, you can use a simple regex to remove all of them in one pass:
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Eliminating new line characters from a string