The java string trim()
method eliminates leading and trailing spaces like if the string s=" hello world "
has whitespace at the starting and end of the string then it removes those spaces and gives you the copy of the string without spaces "hello world"
.
Note-It doesn't remove whitespaces between the strings.
Java trim() Example
- Input: " How are you "
Output: "How are you" //removed leading and trailing whitespaces
- Input: " Hello"
Output: "Hello" //removed leading and trailing whitespaces
Java trim() Syntax
String.trim();
Java trim() Parameter
No parameters are used in this method.
Java trim() Return
The
trim()
method returns a string-- If there is any whitespace in the starting or the end of the string, then it returns a copy of the string without leading and trailing spaces.
- If there is no whitespace in the start or the end, it returns the original string.
Java trim() Program
package codesdope;
import java.util.*;
public class codesdope
{
public static void main(String[] args)
{
String s1=" Welcome to codesdope";
String s2=" Hello world ";
String s3="I love coding";
System.out.println(s1.trim()); //case-1
System.out.println(s2.trim()); //case-2
System.out.println(s3.trim()); //case-3
}
}
Welcome to codesdope
Hello world
I love coding
- In case-1, when we applied the
trim()
method on the string s1 i.e.," Welcome to codesdope
" then it returned a copy of the string without trailing and leading whitespaces. - In case-2, when we applied the
trim()
method on the string s2 i.e.," Hello world "
then it returned a copy of the string without trailing and leading whitespaces. - In the last case, when we applied the
trim()
method on the string s3 i.e.,"I love coding"
then it returned the original string because there are no trailing and leading whitespaces in the string.