 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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
 