Remove leading and trailing spaces in Java

Write a Java program that removes the leading and trailing spaces of the given string.

Java program to remove leading and trailing spaces

public class Main {

    private static final char space = '\u2002';
    private static final String TEXT1 = "\n \n\n  hello  \t \n \r";
    private static final String TEXT2 = space + "\n \n\n  hello  \t \n \r" + space;

    public static void main(String[] args) {

        System.out.println("\\u2002 is whitespace? " + Character.isWhitespace(space));

        System.out.println("\nSolution based on String.trim():");
        String trimmedV1 = TEXT1.trim();
        String trimmedV2 = TEXT2.trim();

        System.out.println("Trimmed text 1:" + trimmedV1);
        System.out.println("Trimmed text 2:" + trimmedV2);

        System.out.println("\nSolution based on String.strip():");
        String strippedV1 = TEXT1.strip();
        String strippedV2 = TEXT2.strip();
        System.out.println("Stripped text 1:" + strippedV1);
        System.out.println("Stripped text 2:" + strippedV2);
    }
}

Output:

\u2002 is whitespace? true

Solution based on String.trim():
Trimmed text 1:hello
Trimmed text 2:?
 

  hello  	 
 
?

Solution based on String.strip():
Stripped text 1:hello
Stripped text 2:hello

Comments