In this tutorial, we will see “How to remove ‘WHITESPACES’ from a String using 2 unique Java methods?” remove whitespaces from string in java
Java – How to remove ‘WHITESPACES’ from a String? – Simplest Example Click To Tweet
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public class Remove_Whitespaces_from_String_Java_Example { public static void main(String[] args) { String str = " Here we have a string with whitespaces "; // Remove leading and trailing whitespaces String strWithoutLeadingandTrailingSpaces = str.strip(); // Remove all whitespaces String strWithoutAnySpace = str.replaceAll("\\s", ""); System.out.println("String without Leading & Trailing spaces: "+strWithoutLeadingandTrailingSpaces); System.out.println("String without any space: "+strWithoutAnySpace); } } |
Output:
1 2 | String without Leading & Trailing spaces: Here we have a string with whitespaces String without any space: Herewehaveastringwithwhitespaces |
remove whitespaces from string in java
The Strip() method was introduced in Java 11 and it removes leading and trailing whitespaces, while the replaceAll() method is a traditional method of removing all whitespaces from a string.
Note: ‘replaceAll()’ method uses a regular expression to match whitespaces (‘\\s’), so it will remove all types of whitespaces including spaces, tabs, and newlines.
skip method java 8 stream
Java – How to remove ‘WHITESPACES’ from a String? – Simplest Example Click To Tweet
Do you like this Post? – then check my other helpful posts:
- Convert a Stream to a List in Java 8
- Stream maptoint in Java 8 with examples
- Double the numbers of specified ArrayList using Streams
- Double the even / odd numbers of a specified ArrayList using Streams
- How to check if Number is Prime or not using Streams
- Retrieve Even/Odd Numbers within the Range using Java 8 Streams
- How to add/sum up the ArrayList integers using Java8 Streams
- Generate Prime Numbers in Java 8 using Streams
- Comparator example – Collections sort with/without Lambda in Java 8
- How to pass function as a parameter in a method in Java 8?
- Remove duplicates from ArrayList in Java 8
- ForEach examples for Map/List in Java 8
Other Useful References: