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:
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:
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:
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.
Java: Tips of the Day
How to sort an ArrayList?
Collections.sort(testList); Collections.reverse(testList);
That will do what you want. Remember to import Collections though!
Ref: https://bit.ly/32urdSe
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework