Java string trim new line

How to Replace Line Breaks , New Lines From String in Java — Windows, Mac or Linux Example

We often need to replace line terminator characters, also known as line breaks e.g. new line \n and carriage return \r with different characters. One of the common case is to replace all line breaks with empty space in order to concatenate multiple lines into one long line of String. In order to replace line breaks, you must know line terminator or new line characters for that platform. For example, In Windows operating system e.g. Windows 7 and 8, lines are terminated by \n\r also known as CR+LF , while in Unix environment e.g. Linux or Solaris line terminator is \n , known as line feed LF . You can also get line terminator pragmatically by using Java system property line.terminator.

Now the question is, How can you replace all line breaks from a string in Java in such a way that will work on both Windows and Linux (i.e. no OS specific problems of carriage return/line feed/new line etc.)?

Читайте также:  Javascript regexp find all matches

Well, You can use System.getProperty(«line.terminator») to get the line break in any OS and by using String replace() method, you can replace all line breaks with any character e.g. white space. replace() method from java.lang.String class also supports regular expressions, which makes it even more powerful.

In next section we will learn how to replace all line breaks from Java String by following a simple code example. By the way, if you are removing line breaks from String then don’t forget to store result of replace() method into same variable.

Since String is immutable in Java, any change on it will always produce a new String, if you assume that call to replace() will change the original string then it’s not going to happen. For example, in below code original String text will remain unchanged, even after calling replace() method.

String word = "Sample String"; word.replace("S", "P"); // will not change text

In order to see the result, you must store String returned by replace() method as shown below :

Now let’s see how to remove new line characters in Java.

Java Program to replace all line breaks from String in Mac, Windows, and Linux

Here is our full code example of removing new line characters like \n or \n\r from Java String. In this sample program, we have two examples, in first example we declare String and insert a new line character by using \n . If you notice, we have also escaped String to show it literally e.g. \\n will display literal ‘\n’ but \n will terminate String in Windows.

Читайте также:  Html manual ru book html php

In Second example, we are reading text from a file and then getting platform’s line terminator by using System property «line.terminator» .

By passing this line break character to replace() method, we can replace all occurrence of characters in String. But there is a catch, this will not work in case you are trying to process a UNIX file on Windows, or vice versa. File must be processed in the environment, where it was written.

/** * Simple Java program which replace line terminating characters like \n (newline) * with empty String to produce single line output of multiple line Strings. * @author Javin Paul */ public class StringReplaceTask< public static void main(String args[]) < // Removing new line characters form Java String String sample="We are going to replace newline character \\n " + "New line should start now if \\n \n is working"; System.out.println("Original String: " + sample); //replacing \n or newline character so that all text come in one line System.out.println("Escaped String: " + sample.replaceAll("\n", "")); // removing line breaks from String read from text file in Java String text = readFileAsString("words.txt"); text = text.replace(System.getProperty("line.separator"), ""); > > Output: Original String: We are going to replace newline character \n New line should start now if \n is working Escaped String: We are going to replace newline character \n New line should start now if \n is working

That’s all on How to replace new line characters or line breaks from String in Java. As I said, you can either directly pass line terminator e.g. \n , if you know the line terminator in Windows, Mac or UNIX . Alternatively you can use following code to replace line breaks in either of three major operating system; str = str.replaceAll(«\\r\\n|\\r|\\n», » «); will replace line breaks with space in Mac, Windows and Linux.

Источник

Java String trim() Method Examples

Java String Trim White Spaces

Some miscellaneous examples with an empty string, string with white spaces only, and string with no leading and trailing white spaces.

jshell> String emptyStr = ""; emptyStr ==> "" jshell> String emptyStrTrim = emptyStr.trim(); emptyStrTrim ==> "" jshell> emptyStr == emptyStrTrim $131 ==> true jshell> String whitespacesStr = " \t\t\n\r "; whitespacesStr ==> " \t\t\n\r " jshell> String whitespacesStrTrim = whitespacesStr.trim(); whitespacesStrTrim ==> "" jshell> String fruit = "Apple"; fruit ==> "Apple" jshell> String fruitTrim = fruit.trim(); fruitTrim ==> "Apple" jshell> fruit == fruitTrim; $136 ==> true

Notice that when the trim() method doesn’t find any leading and trailing white spaces, the reference to this string is returned.

Recommended Read: Java String Pool.

trim() vs strip()

  • The trim() method just checks the Unicode code point and remove them if it’s less than U+0020. The strip() method uses Character and Unicode API to check for white space characters.
  • The trim() method is faster than the strip() method because of its simplicity.
  • You can use trim() method if the string contains usual white space characters – space, tabs, newline, a carriage return.
  • The recommended method is strip() to remove all the leading and trailing white space characters from the string. It uses standard APIs to check for white spaces and more reliable.

Let’s look at an example where the string has special white space characters whose Unicode code point is greater than U+0020.

jshell> String str = "\n\nHello Java \u2000\r\n" str ==> "\n\nHello Java \r\n" jshell> String trimStr = str.trim(); trimStr ==> "Hello Java " jshell> String stripStr = str.strip(); stripStr ==> "Hello Java"

Java String trim vs strip

Notice that strip() method removed “\u2000” (en quad) white space character which was skipped by the trim() method.

Conclusion

Java String trim() method removes leading and trailing white spaces. However, it doesn’t use any standard APIs to check if a character is whitespace or not. It simply removes any character whose Unicode code point is less than or equal to U+0020. That’s why the strip() method was introduced in Java 11. If you are using Java 11 or higher versions, please use the strip() method.

Источник

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.

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

@Test 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 .removeFrom(randomSentence); assertEquals( "Thebackedvalleymanufacturesapoliticianaboveascratchedbody.", removeAllSpaces); >

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.

@Test public void remove_carriage_return_apache()  String randomSentence = "The pocket reflects " + "over an intimate. \r"; String cleanString = StringUtils.chomp(randomSentence); assertEquals( "The pocket reflects over an intimate. ", cleanString); >

Remove newline from string posted by Justin Musgrove on 24 August 2014

Tagged: java and java-string

Источник

Java Trim String

In this Java tutorial, you will learn how to trim all white spaces at the beginning and ending of the string using String.trim() method, with examples.

Java Trim String

To trim all white spaces at the beginning and ending of the string, you can use String.trim() function.

trim() function creates and returns a new string with all the leading and trailing space characters.

trim() considers all the unicode characters from ‘\u0000’ to ‘\u0020’ for trimming at the edges of the string. These set of characters contain all the white space characters like single space, thin space, tab, line feed, carriage return etc.

Syntax of trim()

Following is the syntax of trim() function in String class.

Examples

1. Trim whitespaces from edges of a string

In the following Java program, we initialize a String with some white space characters like single space, new line and new tab. We shall then apply the trim() function to this string and observe the output.

Example.java

Run the above program and you shall see something similar to the following in console window.

"Hello World! Welcome to www.tutorialkart.com"

We have just added leading and trailing double quotes to understand the extent of the resulting string.

The leading and trailing white spaces are gone in the resulting string from trim() function.

Also, note that the white space characters inside the string are preserved. Like the white spaces and new line in this example.

2. Trim String where the string has only whitespace characters in it

In the following Java program, we initialize a String with only white space characters and nothing else.

Example.java

/** * Java Example Program to Trim white space characters at the edges of string */ public class Example < public static void main(String[] args) < //initialize string String str = " \t \n \n\t \n \n \t \r \f \n"; //trim string String result = str.trim(); System.out.print("\""+result+"\""); >>

Run the above program, and you shall get the following in the console output.

The resulting String is just an empty string, since there are no characters with unicode greater than ‘\u0020’.

Conclusion

In this Java Tutorial, we learned how to trim white spaces in a string at the leading and trailing edges.

Источник

Оцените статью