Remove newline from string

This example will show how to remove a carriage return from a string in java. Each operating system newline character could vary and if you are developing a cross platform application, you should pull a system property that defines a line break. The common code looks like System.getProperty("line.separator");. The sentences below were randomly generated online.

Straight up Java

By calling string's replaceAll method we will replace each new line break with an empty space. This uses a regular expression to find the char to replace.

public void remove_carriage_return_java() {

    String text = "Our line rackets \rthe encouraged symmetry.\n";
    String cleanString = text.replaceAll("\r", "").replaceAll("\n", "");

    assertEquals("Our line rackets the encouraged symmetry.", cleanString);

Google Guava

This snippet will show how to remove newlines from a string in java while using guava. CharMatcher is similar to a java predicate in the sense that it determines true or false for a set/range of chars. You can read the code as CharMatcher.BREAKING_WHITESPACE will return true for any character that represents a line break. Calling the remove method will return all non matching values or false of the phrase.

public void remove_carriage_return_guava() {

    String randomSentence = "The backed valley manufactures \r"
            + "a politician above \n" + "a scratched body.";

    String removeAllSpaces = CharMatcher.BREAKING_WHITESPACE


Apache Commons

Apache commons StringUtils.chomp will remove a newline at the end of a String. It does not remove all carriage returns so if that is a need use one of the above methods.

public void remove_carriage_return_apache() {

    String randomSentence = "The pocket reflects "
            + "over an intimate. \r";

    String cleanString = StringUtils.chomp(randomSentence);

            "The pocket reflects over an intimate. ",