
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Remove Whitespace from Beginning and End of a String in Java
In this article, we use the trim() method to remove whitespace at the beginning and end of a string.
This method does not modify the original string; instead, it returns a new string with the leading and trailing whitespace removed.
Let's say the following is our string with whitespace ?
string = " Tutorialspoint ";
Now, let us trim all the whitespaces from the beginning and the end.
String trimmed = string.trim();
Removing whitespace using trim () Method
The trim() method in Java is a built-in function of the String class that removes whitespace from both the beginning and end of a string.
Example
In the following program, we remove leading and trailing whitespace from the string " Tutorialspoint " using the trim() method.
public class RemoveWhitespace { public static void main(String[] args) { String string = " Tutorialspoint "; String trimmed = string.trim(); System.out.println("Original string: '" + string + "'"); System.out.println("Trimmed string: '" + trimmed + "'"); } }
Output
The above program displayed the following output ?
Original string: ' Tutorialspoint ' Trimmed string: 'Tutorialspoint'
Advertisements