In this Java tutorial, you will learn how to trim all white spaces at the beginning and ending of the string using String.trim() method, with examples.
Java Trim String
To trim all white spaces at the beginning and ending of the string, you can use String.trim() function.
trim() function creates and returns a new string with all the leading and trailing space characters.
trim() considers all the unicode characters from ‘\u0000’ to ‘\u0020’ for trimming at the edges of the string. These set of characters contain all the white space characters like single space, thin space, tab, line feed, carriage return etc.
Syntax of trim()
Following is the syntax of trim() function in String class.
public String trim()
Examples
1. Trim whitespaces from edges of a string
In the following Java program, we initialize a String with some white space characters like single space, new line and new tab. We shall then apply the trim() function to this string and observe the output.
Example.java
public class Example {
public static void main(String[] args) {
//initialize string
String str = " \t\n\n\tHello World!\n Welcome to www.tutorialkart.com\n\n\t";
//trim string
String result = str.trim();
System.out.print("\""+result+"\"");
}
}
Run the above program and you shall see something similar to the following in console window.
"Hello World!
Welcome to www.tutorialkart.com"
We have just added leading and trailing double quotes to understand the extent of the resulting string.
The leading and trailing white spaces are gone in the resulting string from trim() function.
Also, note that the white space characters inside the string are preserved. Like the white spaces and new line in this example.
2. Trim String where the string has only whitespace characters in it
In the following Java program, we initialize a String with only white space characters and nothing else.
Example.java
/**
* Java Example Program to Trim white space characters at the edges of string
*/
public class Example {
public static void main(String[] args) {
//initialize string
String str = " \t \n \n\t \n \n \t \r \f \n";
//trim string
String result = str.trim();
System.out.print("\""+result+"\"");
}
}
Run the above program, and you shall get the following in the console output.
Output
""
The resulting String is just an empty string, since there are no characters with unicode greater than ‘\u0020’.
Conclusion
In this Java Tutorial, we learned how to trim white spaces in a string at the leading and trailing edges.