w3resource

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

Java String: Exercise-31 with Solution

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

Visual Presentation:

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

Sample Solution:

Java Code:

// Define a public class named Exercise31.
public class Exercise31 {

    // Define the main method.
    public static void main(String[] args) {
        // Declare and initialize a string variable.
        String str = " Java Exercises ";

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

        // Display the original and trimmed 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

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: Write a Java program to find longest Palindromic Substring within a string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/java-exercises/string/java-string-exercise-31.php