w3resource logo
Java Programming Exercies

Java String Exercises: Trim any leading or trailing whitespace from a given string

Java String : Exercise-31 with Solution

Write a Java program to trim any leading or trailing whitespace from a given string.

Sample Solution:

Java Code:

public class Exercise31 {

public static void main(String[] args)
    {
        String str = " Java Exercises ";

        // Trim the whitespace from the front and back of the
        // String.
        String new_str = str.trim();

        // Display the strings for comparison.
System.out.println("Original String: " + str);
System.out.println("New String: " + new_str);
    }
}

Sample Output:

Original String:  Java Exercises                                                                              
New String: Java Exercises

Java Code Editor:

public class Exercise31 {

public static void main(String[] args)
    {
        String str = " Java Exercises ";

        // Trim the whitespace from the front and back of the
        // String.
        String new_str = str.trim();

        // Display the strings for comparison.
System.out.println("Original String: " + str);
System.out.println("New String: " + new_str);
    }
}

Improve this sample solution and post your code through Disqus