Saturday, September 6, 2025
HomeLanguagesJavaJava Program to Replace All Line Breaks from Strings

Java Program to Replace All Line Breaks from Strings

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
RELATED ARTICLES

Most Popular

Dominic
32270 POSTS0 COMMENTS
Milvus
82 POSTS0 COMMENTS
Nango Kala
6639 POSTS0 COMMENTS
Nicole Veronica
11803 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11869 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7029 POSTS0 COMMENTS
Thapelo Manthata
6705 POSTS0 COMMENTS
Umr Jansen
6721 POSTS0 COMMENTS