Sunday, December 29, 2024
Google search engine
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

Recent Comments