Open In App

Java Program to Replace All Line Breaks from Strings

Last Updated : 28 Oct, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Given a string, write a Java program to replace all line breaks from the given String.

Examples

Input - Geeks
        For
        Geeks
        
Output - Geeks For Geeks

Line Break: A line break (“\n”) is a single character that defines the line change. 

In order to replace all line breaks from strings replace() function can be used.

String replace(): This method 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

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads