String
String trim method
This is an example of how to use the trim
method of String class. The String class represents character strings. All string literals in Java programs, such as "abc"
, are implemented as instances of this class. Trimming a String implies that you should:
- Create a new String.
- Use
trim()
method of String. This method returns a copy of the string, with leading and trailing whitespace omitted. If this String object represents an empty character sequence, or the first and last characters of character sequence represented by this String object both have codes greater than'\u0020'
(the space character), then a reference to this String object is returned.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; public class StringTrimMethod { public static void main(String[] args) { String s = " Java Code Geeks "; System.out.println("Original String:'" + s + "'"); // remove leading and trailing space from string use String sTrimmed = s.trim(); System.out.println("Trimmed String:'" + sTrimmed + "'"); } }
Output:
Original String:' Java Code Geeks '
Trimmed String:'Java Code Geeks'
This was an example of how to trim
method of String in Java.