Skip to content
Related Articles

Related Articles

Java Program to Replace All Line Breaks from Strings
  • Last Updated : 05 Feb, 2021

Line break (“\n”) is a single character, to replace all line breaks from strings replace() function can be used.

String replace(): returns a new String object that contains the same sequence of characters as the original string, but with a given character replaced by another given character.

Syntax:

public String replace(char old,char new)

Parameters:

  • old: old character
  • new: new character

Returns value: Returns a string by replacing an old character with the new character

Java




// Java Program to Replace All Line Breaks from Strings
public class remove {
    public static void main(String[] args)
    {
        String s = "Replace\n"
                   + " all\n"
                   + " line\n"
                   + " breaks\n"
                   + " from\n"
                   + " strings";
        
        System.out.println(
            "Original String with line breaks:" + s);
        
        // replacing line breaks from string
        s = s.replace("\n", "");
        
        System.out.println(
            "String after replacing line breaks:" + s);
    }
}
Output
Original String with line breaks:Replace
 all
 line
 breaks
 from
 strings
String after replacing line breaks:Replace all line breaks from strings

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :