How to remove leading and trailing whitespaces from a string?

To remove leading and trailing spaces in Java, use the trim(), stripTrailing() and stripLeading() method. This method returns a copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space

Example:

Input:  str ="  Hello World!!  "
Output: Remove Trailing space:  Hello World!!
        Remove Leading spacee:Hello World!!  
        Remove Leading and Trailing spacee:Hello World!!

Approach

Java


public class HelloWorld {
    public static void main(String[] args) {
        String str = "  Hello World!!  ";
        System.out.println("Remove Trailing space:" + str.stripTrailing());
        System.out.println("Remove Leading spacee:" + str.stripLeading());
        System.out.println("Remove Leading and Trailing spacee:" + str.trim());
    }
}


No comments:

Post a Comment