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 Share on X

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:

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 Share on X

Do you like this Post? – then check my other helpful posts:

Other Useful References:

Author

  • Deepak Verma

    Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester.

    He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks.

    View all posts