java 8 remove spaces from string

‮/:sptth‬/www.lautturi.com
java 8 remove spaces from string

To remove spaces from a string in Java 8 and later, you can use the replaceAll method of the String class and specify a regular expression that matches one or more spaces.

Here is an example of how you can use the replaceAll method to remove spaces from a string:

String str = "   Hello,   World!   ";
String result = str.replaceAll("\\s+", "");
System.out.println(result); // Outputs "Hello,World!"

In this example, the replaceAll method uses the regular expression "\\s+" to match one or more spaces in the string. The replaceAll method replaces the matched spaces with an empty string, resulting in a string with all spaces removed.

It is important to note that the replaceAll method returns a new string, and it does not modify the original string. If you want to modify the original string, you can use the replaceAll method and assign the result to the original string, like this:

str = str.replaceAll("\\s+", "");

Alternatively, you can use the trim method of the String class to remove leading and trailing spaces from a string, like this:

String str = "   Hello,   World!   ";
String result = str.trim();
System.out.println(result); // Outputs "Hello,   World!"

The trim method removes leading and trailing spaces from the string, but it does not remove spaces within the string. If you want to remove all spaces from the string, you can use the replaceAll method as shown in the first example.

Created Time:2017-11-01 22:29:54  Author:lautturi