supercache_stats

Remove Leading / Trailing Whitespaces in Java

This tutorial demonstrates how to trim the leading and/or trailing whitespaces from a Java String using regular expressions and a new String.strip() API in Java 11.

1. Introduction

The whitespaces at the beginning of a String are called leading whitespaces, and trailing whitespaces are at the String’s end. Though we can use the regex and other methods to trim the spaces, using the strip() methods have been recommended since Java 11.

2. Remove the Leading Whitespaces

2.1. Using String.stripLeading()

The stripLeading() method has been added in Java 11. It returns a string with all leading white spaces removed.

String blogName = "    how to do in java    ";
String strippedLeadingWhitespaces = blogName.stripLeading();

Assertions.assertEquals(strippedLeadingWhitespaces, "how to do in java    ");

2.2. Using Regular Expression

This Java example utilizes regular expression with String’s replaceAll() method to find all leading whitespaces. Once we have all the leading whitespaces, we can replace them with an empty string.

String regex = "^\\s+";

String trimmedLeadingWhitespaces = blogName.replaceAll(regex, "");

Assertions.assertEquals(trimmedLeadingWhitespaces, "howtodoinjava    ");

Or we can use the same regex to match the whitespaces at the beginning to String using replaceFirst() method.

String regex = "^\\s+";
String trimmedLeadingWhitespaces = blogName.replaceFirst(regex, "");

Assertions.assertEquals("howtodoinjava    ", trimmedLeadingWhitespaces);

2. Remove the Trailing Whitespaces

2.1. Using String.stripTrailing()

The stripTrailing() method returns a string with all trailing white space removed.

String blogName = "    how to do in java    ";
String strippedTrailingWhitespaces = blogName.stripTrailing();

Assertions.assertEquals(strippedTrailingWhitespaces , "how to do in java    ");

2.2. Using Regular Expression

The approach to remove the whitespaces from the end of String is very similar to the previous example. Only the regex changes to match from the end.

String regex = "\\s+$";

String trimmedTrailingWhitespaces = blogName.replaceAll(regex, "");
Assertions.assertEquals("    how to do in java", trimmedTrailingWhitespaces);

3. Remove Leading as well as Trailing Whitespaces

3.1. Using String.trim()

If we want to remove surrounding whitespaces from string, then the best way is to use String.trim() method.

String blogName = "    how to do in java    ";

String trimmedString = blogName.trim();
Assertions.assertEquals("how to do in java", trimmedString);

3.1. Using String.strip()

We can also use the strip() method, which has been available since Java 11.

String blogName = "    how to do in java    ";

String strippedString = blogName.strip();
Assertions.assertEquals("how to do in java", strippedString);

Use the above-given examples to trim leading and trailing white spaces from String in Java.

Happy Learning !!

Leave a Comment