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

What is the difficulty level of this exercise?



Java: Tips of the Day

Array vs ArrayLists:

The main difference between these two is that an Array is of fixed size so once you have created an Array you cannot change it but the ArrayList is not of fixed size. You can create instances of ArrayLists without specifying its size. So if you create such instances of an ArrayList without specifying its size Java will create an instance of an ArrayList of default size.

Once an ArrayList is full it re-sizes itself. In fact, an ArrayList is internally supported by an array. So when an ArrayList is resized it will slow down its performance a bit as the contents of the old Array must be copied to a new Array.

At the same time, it's compulsory to specify the size of an Array directly or indirectly while creating it. And also Arrays can store both primitives and objects while ArrayLists only can store objects.

Ref: https://bit.ly/3o8L2KH