
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
Trim a String in Java to Remove Leading and Trailing Spaces
To remove leading and trailing spaces in Java, use the trim() method. This method returns a copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.
Let’s say the following is our string with leading and trailing spaces −
String str = new String(" Jack Sparrow ");
Now, let us trim the string −
str.trim()
Following is an example to remove the leading and trailing spaces in Java −
Example
import java.io.*; public class Main { public static void main(String args[]) { String str = new String(" Jack Sparrow "); System.out.println("String: "+str); System.out.print("Result after removing leading and trailing spaces:" ); System.out.println(str.trim() ); } }
Output
String: Jack Sparrow Result after removing leading and trailing spaces:Jack Sparrow
Advertisements