w3resource

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.

Pictorial Presentation:

Java String Exercises: 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

Flowchart:

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

Visualize Java code execution (Python Tutor):


Remove Whitespaces from a given string.

Main.java Code:

//MIT License: https://bit.ly/35gZLa3
import java.util.concurrent.TimeUnit;

public class Main {

    private static final String TEXT = "      My high\n\n school,        the Illinois Mathematics and Science Academy, "
            + "showed me that anything is possible and that you're never too young to think big. \r"
            + "At 15, I worked as a computer programmer at the Fermi National Accelerator Laboratory, \t"
            + "or Fermilab. After graduating, I attended Stanford for a degree in economics and "
            + "computer science.           ";

    public static void main(String[] args) {

        System.out.println("Input text: \n" + TEXT + "\n");

        System.out.println("replaceAll() solution:");
        long startTime = System.nanoTime();

        String result = Strings.removeWhitespaces(TEXT);

        displayExecutionTime(System.nanoTime() - startTime);
        System.out.println("String without blanks is: \n" + result);
    }

    private static void displayExecutionTime(long time) {
        System.out.println("Execution time: " + time + " ns" + " ("
                + TimeUnit.MILLISECONDS.convert(time, TimeUnit.NANOSECONDS) + " ms)");
    }
}

Strings.java Code:

//MIT License: https://bit.ly/35gZLa3
public final class Strings {

    private Strings() {
        throw new AssertionError("Cannot be instantiated");
    }

    public static String removeWhitespaces(String str) {

        if (str == null || str.isEmpty()) {
            // or throw IllegalArgumentException
            return "";
        }

        return str.replaceAll("\\s", "");
    }

}

Sample Output:

Input text: 
      My high

 school,        the Illinois Mathematics and Science Academy, showed me that anything is possible and that you're never too young to think big. 
At 15, I worked as a computer programmer at the Fermi National Accelerator Laboratory, 	or Fermilab. After graduating, I attended Stanford for a degree in economics and computer science.           

replaceAll() solution:
Execution time: 2846329 ns (2 ms)
String without blanks is: 
Myhighschool,theIllinoisMathematicsandScienceAcademy,showedmethatanythingispossibleandthatyou'renevertooyoungtothinkbig.At15,IworkedasacomputerprogrammerattheFermiNationalAcceleratorLaboratory,orFermilab.Aftergraduating,IattendedStanfordforadegreeineconomicsandcomputerscience.

Flowchart:

Flowchart: Java String Exercises - Remove Whitespaces From String
Flowchart: Java String Exercises - Remove Whitespaces From String

Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program to convert all the characters in a string to uppercase.
Next: Java Date, Time and Calendar Exercises

What is the difficulty level of this exercise?