Remove Whitespace from Beginning and End of a String in Java



In this article, we use the trim() method to remove whitespace at the beginning and end of a string.

This method does not modify the original string; instead, it returns a new string with the leading and trailing whitespace removed.

Let's say the following is our string with whitespace ?

string = "   Tutorialspoint  ";

Now, let us trim all the whitespaces from the beginning and the end.

String trimmed = string.trim();

Removing whitespace using trim () Method

The trim() method in Java is a built-in function of the String class that removes whitespace from both the beginning and end of a string.

Example

In the following program, we remove leading and trailing whitespace from the string " Tutorialspoint " using the trim() method.

public class RemoveWhitespace {
    public static void main(String[] args) {

        String string = "   Tutorialspoint  ";
        String trimmed = string.trim();
        
        System.out.println("Original string: '" + string + "'");
        System.out.println("Trimmed string: '" + trimmed + "'");
    }
}

Output

The above program displayed the following output ?

Original string: '   Tutorialspoint  '
Trimmed string: 'Tutorialspoint'
Revathi Satya Kondra
Revathi Satya Kondra

Technical Content Writer, Tutorialspoint

Updated on: 2024-12-31T11:18:24+05:30

494 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements