Given a string, remove all the leading and trailing spaces from the string and return it.
Input : str = " Hello World " Output : str = "Hello World" Input : str = " Hey there Joey!!! " Output : str = "Hey there Joey!!!"
- We can eliminate the leading and trailing spaces of a string in Java with the help of trim().
- trim() method is defined under the String class of java.lang package.
- It does not eliminated the middle spaces of the string.
- By calling the trim() method, a new String object is returned.
- It doesn’t replace the value of String object. Therefore if we want the access to the new String object, we just need to reassign it to the old String or assign it to a new variable.
How it works?
For space character the unicode value is ‘\u0020’. This method checks for this unicode value before and after the string and if it exists then eliminates the spaces(leading and trailing) and returns the string (without leading and trailing spaces).
Hello World Hello World Hey there Joey!!! Hey there Joey!!!
This article is contributed by Kishlay Verma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.
- Remove Leading Zeros From String in Java
- How to remove all white spaces from a String in Java?
- Java String trim() method with Example
- Remove first and last character of a string in Java
- Remove all non-alphabetical characters of a String in Java
- How to remove all non-alphanumeric characters from a string in Java
- Remove extra delimiter from a String in Java
- Different Ways to Remove all the Digits from String in Java
- ArrayList and LinkedList remove() methods in Java with Examples
- Remove a given word from a String
- How to remove an element from ArrayList in Java?
- TreeSet remove() Method in Java
- EnumMap remove() Method in Java
- LinkedList remove() Method in Java
- HashSet remove() Method in Java
- PriorityQueue remove() Method in Java
- HashMap remove() Method in Java
- TreeMap remove() Method in Java
- ArrayDeque remove() Method in Java
- WeakHashMap remove() method in Java