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.
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.
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.