StringUtils stripEnd() Example in Java

In this post, we will see org.apache.commons.lang3.StringUtils stripEnd() example in Java. The stripEnd() method is used to check given character is a space or not. It returns true if the given character is only space else returns false.

The stripEnd() method from the StringUtils class in Java can be useful in many situations where we need to remove trailing characters from a string. Let’s see few examples:

Removing whitespace from the end of a string: If you have a string with extra spaces at the end, you can use stripEnd() to remove them. For example:

String str = "  hello world   ";
String stripped = StringUtils.stripEnd(str, " ");
System.out.println(stripped); // output: "  hello world"

Removing trailing zeros from a number: If you have a number represented as a string with trailing zeros, you can use stripEnd() to remove them. For example:

String numStr = "123.45000";
String stripped = StringUtils.stripEnd(numStr, "0");
System.out.println(stripped); // output: "123.45"

Removing a specific character from the end of a string: If you have a string with a specific character at the end that you want to remove, you can use stripEnd() to do so. For example:

String str = "hello world!";
String stripped = StringUtils.stripEnd(str, "!");
System.out.println(stripped); // output: "hello world"

StringUtils stripEnd() Example in Java

import org.apache.commons.lang3.StringUtils;

public class Example {
    public static void main(String[] args) {
        String str = "  hello world   ";
        String stripped = StringUtils.stripEnd(str, " ");
        System.out.println(stripped);
    }
}

The output of the above example is

hello world" (without the trailing spaces).

In this example, we import the StringUtils class from the Apache Commons Lang library. We then create a String called str that contains some whitespace at the beginning and end of the string.

Next, we call the stripEnd() method on the StringUtils class and pass in the str variable as the first argument, and " " (a single space character) as the second argument. This tells the method to remove all trailing space characters from the end of the string.

We need to add the below dependency in maven to use org.apache.commons.lang3.StringUtils stripEnd() method. We can download the apache-commons maven dependency from here.

Note – The StringUtils class provides a different method contains() to check string contains whitespace or not.

pom.xml changes

<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.10</version>
</dependency>

That’s all about StringUtils stripEnd() example in Java.

Related post.