Open In App

String Class stripTrailing() Method in Java with Examples

Last Updated : 30 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

This method is used to strip trailing whitespaces from the string i.e. stripTrailing() method removes all the whitespaces only at the ending of the string. 

Example:

Input:

String name = "   kapil   ";
System.out.println("#" + name + "#");
System.out.println("#" + name.stripTrailing() + "#");


Output:

#   kapil   #
#   kapil#    // trailing whitespaces are removed 

Explanation:

  • name.stripTrailing(): This method removes trailing whitespaces from the string name.

The output correctly shows:

  • The first line with leading and trailing spaces intact: # kapil #.
  • The second line with trailing spaces removed: # kapil#.

Syntax:

public String stripTrailing()
  • Parameter: It accepts no parameters.
  • Returns: The string after removing all the whitespaces at the end of the string.

Note: Like the stripTrailing() method in java, we have strip() (removes leading and trailing whitespace) and stripLeading() (removes the only leading whitespace). 

Java
// Java program to demonstrate the usage of
// stripTrailing() method in comparison to 
// other methods

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

        // creating a string
        String str = "  Hello,  World ";

        // print the string without any function
        System.out.println("String is");
        System.out.println("#" + str + "#");
        System.out.println();

        // using strip() method
        System.out.println("Using strip()");
        System.out.println("#" + str.strip() + "#");
        System.out.println();

        // using stripLeading() method
        System.out.println("Using stripLeading()");
        System.out.println("#" + str.stripLeading() + "#");
        System.out.println();

        // using stripTrailing() method
        System.out.println("Using stripTrailing()");
        System.out.println("#" + str.stripTrailing() + "#");
    }
}

Output
String is
#  Hello,  World #

Using strip()
#Hello,  World#

Using stripLeading()
#Hello,  World #

Using stripTrailing()
#  Hello,  World#

Explanation of the above Program:

This Java program demonstrates the use of the strip(), stripLeading(), and stripTrailing() methods to manipulate whitespaces in a string.

  • Original String: The string " Hello, World " is printed with leading and trailing whitespaces intact.
  • Using strip(): This method removes both leading and trailing whitespaces from the string.
  • Using stripLeading(): This method removes only the leading (left-side) whitespaces.
  • Using stripTrailing(): This method removes only the trailing (right-side) whitespaces.




Next Article
Article Tags :
Practice Tags :

Similar Reads