Core Java

Remove Only Trailing Whitespace From a String in Java

In programming, handling whitespace characters within strings often requires careful manipulation, especially when dealing with leading or trailing spaces. Trailing spaces refer to whitespace characters (such as spaces or tabs) that appear at the end of a String while leading spaces occur at the beginning. This article focuses on techniques to specifically remove trailing spaces from strings using various Java methods and libraries.

1. Understanding Trailing and Leading Whitespaces

Whitespaces are non-printable characters like spaces, tabs, or line breaks. Trailing whitespaces are those found at the end of a string, which could be unintentionally inserted during input processing or manipulating strings. Leading whitespaces are similarly located at the start of a string.

For instance, consider the string "Hello World " (with extra spaces at the end). The trailing spaces here are the ones occurring after "World".

2. Using Regular Expressions (Regex) and replaceAll() Method

One straightforward method to remove trailing spaces is through regular expressions (regex) using Java’s String.replaceAll() method.

public class RemoveWhiteSpaceRegex {

    public static void main(String[] args) {

        String str = "Alice in Wonderland     ";
        String trimmed = str.replaceAll("\\s+$", "");
        System.out.println(trimmed); // Output: "Alice in Wonderland"
        
    }
}

In this snippet, \\s+$ is a regex pattern that matches one or more whitespace characters (\\s+) at the end of the string ($). The replaceAll() method replaces these trailing spaces with an empty string.

  • \\s+ matches one or more whitespace characters (spaces or tabs).
  • $ signifies the end of the string.
  • replaceAll() replaces all occurrences of the matched pattern (trailing whitespace) with an empty string.

3. Java 11 and Later: stripTrailing() Method

Starting from Java 11, the String class provides a built-in method stripTrailing() specifically designed to remove trailing whitespaces:

public class StripTrailingExample {

    public static void main(String[] args) {

        String str = "Hello World    ";
        String trimmed = str.stripTrailing();
        System.out.println(trimmed); // Output: "Hello World"

    }
}

The stripTrailing() method returns a string with all trailing whitespaces removed. It’s a more readable and efficient alternative compared to manual regex operations.

4. Apache Commons Lang 3’s stripEnd() Method

Using the Apache Commons Lang library (specifically version 3 or later), we can leverage the StringUtils.stripEnd() method to achieve the same result. First, add the dependency for Commons Lang in the pom.xml file:

    <dependencies>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.12.0</version> <!-- Specify the version you want to use -->
        </dependency>
   </dependencies>
import org.apache.commons.lang3.StringUtils;

public class RemoveWhitespaceApacheLangLib {

    public static void main(String[] args) {

        String str = "The Three Musketeers     ";
        String trimmed = StringUtils.stripEnd(str, null);
        System.out.println(trimmed); // Output: "The Three Musketeers"
        
    }
}

Here, StringUtils.stripEnd() removes trailing whitespace characters from the given string. The second argument (null in this case) specifies the characters to strip; null means all whitespace characters.

Fig 1: program output - remove only trailing whitespace using Apache Commons Lang 3’s
Fig 1: program output – remove only trailing whitespace using Apache Commons Lang 3’s

5. Conclusion

Removing trailing spaces from strings is a common task in programming, especially when dealing with user inputs or data processing. Understanding the difference between leading and trailing whitespaces is crucial for effective string manipulation.

With Java’s built-in methods like replaceAll(), stripTrailing(), or libraries like Apache Commons Lang, we can efficiently handle and clean strings by removing unwanted trailing whitespaces, ensuring our applications handle data accurately.

6. Download the Source Code

This was an example of how to remove only trailing whitespace from a String in Java.

Download
You can download the full source code of this example here: Remove only trailing whitespace from a String in Java

Omozegie Aziegbe

Omos Aziegbe is a technical writer and web/application developer with a BSc in Computer Science and Software Engineering from the University of Bedfordshire. Specializing in Java enterprise applications with the Jakarta EE framework, Omos also works with HTML5, CSS, and JavaScript for web development. As a freelance web developer, Omos combines technical expertise with research and writing on topics such as software engineering, programming, web application development, computer science, and technology.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button