Friday, April 4, 2014

How to replace line breaks , New lines from String in Java.- Windows, Mac or Linux

We often need to replace line terminator characters, also known as line breaks e.g. new line \n and carriage return \r with different characters. One of the common case is to replace all line breaks with empty space in order to concatenate multiple lines into one long line of String. In order to replace line breaks, you must know line terminator or new line characters for that platform. For example, In Windows operating system e.g. Windows 7 and 8, lines are terminated by \n\r also known as CR+LF, while in Unix environment e.g. Linux or Solaris line terminator is \n, known as line feed LF. You can also get line terminator pragmatically by using Java system property line.terminator. Now question is, How can you replace all line breaks from a string in Java in such a way that will work on both Windows and Linux (i.e. no OS specific problems of carriage return/line feed/new line etc.)? Well, You can use System.getProperty("line.terminator") to get the line break in any OS and by using String replace() method, you can replace all line breaks with any character e.g. white space. replace() method from java.lang.String class also supports regular expressions, which makes it even more powerful. In next section we will learn how to replace all line breaks from Java String by following a simple code example. By the way, if you are removing line breaks from String then don't forget to store result of replace() method into same variable. Since String is immutable in Java, any change on it will always produce a new String, if you assume that call to replace() will change the original string then it's not going to happen. For example, in below code original String text will remain unchanged, even after calling replace() method.
Read more �

No comments:

Post a Comment