Wednesday, July 28, 2021

How to Replace Line Breaks , New Lines From String in Java - Windows, Mac or Linux Example

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


String word = "Sample String";
word.replace("S", "P"); // will not change text

In order to see the result, you must store String returned by replace() method as shown below :

word = word.replace("S", "P");

Now let's see how to remove new line characters in Java.




Java Program to replace all line breaks from String in Mac, Windows, and Linux

How to replace line breaks from Java String in Windows, Mac and Linux
Here is our full code example of removing new line characters like \n or \n\r from Java String. In this sample program, we have two examples, in first example we declare String and insert a new line character by using \n. If you notice, we have also escaped String to show it literally e.g. \\n will display literal '\n' but \n will terminate String in Windows. 




In Second example, we are reading text from a file and then getting platform's line terminator by using System property "line.terminator"

By passing this line break character to replace() method, we can replace all occurrence of characters in String. But there is a catch, this will not work in case you are trying to process a UNIX file on Windows, or vice versa. File must be processed in the environment, where it was written.

/**
  * Simple Java program which replace line terminating characters like \n (newline)
  * with empty String to produce single line output of multiple line Strings.
 
  * @author Javin Paul
  */
public class StringReplaceTask{
   
   
    public static void main(String args[]) {
     
 // Removing new line characters form Java String
        String sample="We are going to replace newline character \\n "
                + "New line should start now if \\n \n is working";
        System.out.println("Original String: " + sample);
       
        //replacing \n or newline character so that all text come in one line
        System.out.println("Escaped String: " + sample.replaceAll("\n", ""));


 // removing line breaks from String read from text file in Java
 String text = readFileAsString("words.txt");
 text = text.replace(System.getProperty("line.separator"), "");
       
    }  
  
}

Output:
Original String: We are going to replace newline character \n New line 
should start now if \n 
 is working
Escaped String: We are going to replace newline character \n New line 
should start now if \n  is working


That's all on How to replace new line characters or line breaks from String in Java. As I said, 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", " "); will replace line breaks with space in Mac, Windows and Linux.

No comments :

Post a Comment