How to Remove Newline Characters in Java String

Save

Line breaks, represented by the "\n" newline character, allow a Java string to be broken up into multiple lines when it is displayed. Unfortunately, this may not be what is desired, particularly if the programmer wants to translate a block of text from hard line breaks to soft line breaks with word-wrapping. Removing newline characters is as easy as replacing them with empty strings with the "String.replace" command.

  • Open your favorite text editor or Java Integrated Development Environment and create a new class. Netbeans IDE comes with the Java SDK by default, but the code can be completed with any text editor or IDE.

  • Type "psvm" to create a main method. Alternatively, if you are using another text editor, type the following to define a simple skeleton class:

    public class RemoveNewLines {

    public static void main(String[] args) {

    }

    }

  • Paste the following within the main method:

    String s = removeNewlines("This is \n string with new lines.");

    System.out.println(s);

    This calls a function named "removeNewLines" on a sentence that has a newline character "\n" in it. Unfortunately, this function doesn't exist yet, so you need to create it.

  • Add the following code immediately above the main method:

    static String removeNewlines(String s) {

    s = s.replace("\n", "");

    return s;

    }

    This replaces every instance of the new line character "\n" with an empty string and returns the result.

  • Click "Run."

References

Promoted By Zergnet

Comments

You May Also Like

Related Searches

M
Is DIY in your DNA? Become part of our maker community.
Submit Your Work!