1. Overview
In this tutorial, we’ll explore the various strip methods in the String class. We’ll demonstrate their use and understand under which circumstances we should use one over another. Finally, we’ll compare and contrast these methods against the trim() method of the String class.
Let’s pretend for this article that we have the following String:
String s = " Baeldung ";
We can note the whitespace at the start and end of this String.
2. The Strip Methods
With Java 11, we saw the introduction of the strip(), stripLeading() and stripTrailing() methods, with the addition of the stripIndent() method in Java 13. All these methods have one thing in common, they remove whitespace according to the same definition. This definition is that a given character is considered whitespace if its equivalent Unicode code point returns true for the Character.isWhitespace() method.
2.1. The strip() Method
We can use the strip() method when we want to remove whitespace from both the start and end of our String:
@Test
void givenString_whenUsingStripMethod_thenRemoveTrailingLeadingWhitespace() {
assertThat(s.strip())
.doesNotStartWith(" ")
.doesNotEndWith(" ")
.isEqualTo("Baeldung");
}
Consequently, we get a new String of just “Baeldung” with no whitespace at the front or end of the String. It’s worth understanding why we specify a “new” String. This is because the String class is immutable (the state of an instance of a class cannot change once instantiated). As a result, a method such as the strip() method, creates a new String object and returns a reference to this object which reflects the desired state.
If our String only contained whitespace, then the strip() method would return an empty String:
@Test
void givenWhitespaceString_whenUsingStripMethod_thenObtainEmptyString() {
assertThat(" ".strip()).isEmpty();
}
2.2. The stripLeading() Method
If we want to remove only the leading whitespace, the whitespace at the beginning of our String, we can use the stripLeading() method:
@Test
void givenString_whenUsingStripLeadingMethod_thenRemoveLeadingWhitespace() {
assertThat(s.stripLeading())
.doesNotStartWith(" ")
.endsWith(" ")
.isEqualTo("Baeldung ");
}
Notably, in our assertion, the String still has the whitespace at the end of the String.
This method also returns an empty String if the String contains only whitespace:
@Test
void givenWhitespaceString_whenUsingStripLeadingMethod_thenObtainEmptyString() {
assertThat(" ".stripLeading()).isEmpty();
}
2.3. The stripTrailing() Method
If we have the opposite requirement of removing only the trailing whitespace, we can use the stripTrailing() method instead:
@Test
void givenString_whenUsingStripTrailingMethod_thenRemoveTrailingWhitespace() {
assertThat(s.stripTrailing())
.startsWith(" ")
.doesNotEndWith(" ")
.isEqualTo(" Baeldung");
}
Here in our assertion that our String still has the whitespace at the start.
If our String is only whitespace, this method also returns an empty String:
@Test
void givenWhitespaceString_whenUsingStripTrailingMethod_thenObtainEmptyString() {
assertThat(" ".stripTrailing()).isEmpty();
}
2.4. The stripIndent() Method
Java 15 introduced support for text blocks. Text blocks allow us to instantiate a String whose value is across multiple lines.
Let’s consider the following text block:
String textBlock = """
B
a
e
l
d
u
n
g""";
We can use the stripIndent() method to remove the incidental whitespace from each line. In our case, the incidental whitespace is the amount of whitespace on the line before the letter ‘B‘. Each new line contains an additional space which is considered deliberate and thus, after indenting using this method, the relative positioning of the other lines is retained:
@Test
void givenTextBlockWithExtraSpaceForEachNewLine_whenUsingStripIndent_thenIndentTextBlock() {
String textBlock = """
B
a
e
l
d
u
n
g""";
assertThat(textBlock.stripIndent())
.isEqualTo("B\n a\n e\n l\n d\n u\n n\n g");
}
As we can see, we get a String whereby no whitespace exists for the first line. In addition, the other lines keep their relative positioning by retaining the appropriate non-incidental whitespace.
To better demonstrate how the lines retain their positional nature, let’s consider the following text block as well:
@Test
void givenTextBlockWithFourthLineAsLeftMost_whenUsingStripIndent_thenIndentTextBlock() {
String textBlock = """
B
a
e
l
d
u
n
g""";
assertThat(textBlock.stripIndent())
.isEqualTo(" B\n a\n e\nl\n d\n u\n n\n g");
}
As we can see, the stripIndent() method indents the line with the String ‘l‘ fully to the left whilst the other lines retain their relative positioning.
3. Comparing the Strip Methods vs the trim() Method
The String class has another method that removes whitespace, the trim() method. However, the strip methods and the trim() method have one important difference. Each has its definition of what whitespace is. That being said, the trim() method is similar to the strip() method in that both methods remove leading and trailing whitespace.
3.1. The trim() Method
As we previously discussed, the strip methods define whitespace based on whether or not a character satisfies the Character.isWhitespace() method.
However, the trim() method defines whitespace as characters whose code points fall within the range of U+0000 (the null character) and U+0020 (the space character) inclusively.
Thus, let’s consider a String that contains a Unicode code point within this range:
@Test
void givenStringWithUnicodeForNull_whenUsingTrimMethod_thenRemoveUnicodeForNull() {
assertThat("Baeldung\u0000".trim()).isEqualTo("Baeldung");
}
We can see that when using the trim() method the null character has been considered whitespace and thus removed.
For demonstration purposes, let’s consider a String that has a Unicode code point outside of the range that trim() considers whitespace:
@Test
void givenStringWithUnicodeForExclamationMark_whenUsingTrimMethod_thenObtainOriginalStringValue() {
assertThat("Baeldung\u0021".trim()).isEqualTo("Baeldung!");
}
The exclamation mark has not been removed from our String. It’s worth noticing how we can use the Unicode code point or exclamation mark interchangeably.
3.2. The strip() Method vs the trim() Method
Now, that we know how the trim() method works, let’s compare it against the strip() method. Let’s demonstrate a scenario whereby each method produces a different result when using the same String.
Previously, we discovered how the trim() method removed the null character from our String as it’s considered whitespace. However, for the strip() method, null isn’t considered as whitespace according to the Character.isWhitespace() definition:
@Test
void givenStringWithUnicodeForNull_whenUsingStripMethod_thenObtainOriginalStringValue() {
assertThat("Baeldung\u0000".strip()).isEqualTo("Baeldung\u0000");
}
As we can see, we retain the null Unicode code point when using the strip() method in contrast to the trim() method.
4. Conclusion
In this article, we learned about the different strip methods available in the String class and demonstrated their use. Furthermore, we discovered how the strip methods and trim() method each define whitespace. This allowed us to demonstrate the subtle difference when using these methods on different Strings.
As always, the code samples used in this article are available over on GitHub.