This week's book giveaway is in the Performance forum.
We're giving away four copies of The Java Performance Companion and have Charlie Hunt, Monica Beckwith, Poonam Parhar, & Bengt Rutisson on-line!
See this thread for details.
Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Eliminating new line characters from a string

 
Barry Brashear
Ranch Hand
Posts: 303
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 49442
62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
replaceAll method of String?

myString.replaceAll("\n", "");
 
Jeff Storey
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Rancher
Posts: 42968
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Alan Moore
Ranch Hand
Posts: 262
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic