Trim
In Java, strings often contain leading or trailing whitespace. For processing the string
data, these spaces are not always useful, and sometimes they cause issues.
With the trim method, we remove them. Trim
in Java removes whitespace (including newlines, tabs and spaces) from both the left and right. Custom methods may be used for more specific purposes.
This program declares and populates an array of 5 strings. These strings have leading or trailing whitespace—spaces, tabs and newlines.
Trim()
is called on the string
to be trimmed, which must not be null
. It returns a new, modified string
.trim()
to a variable (or pass it directly to a method) for it to be of any use.public class Program { public static void main(String[] args) { String[] values = { " cat", "dog ", " =bird= ", "fish\t", "line\n\n\n" }; // Trim each value in the string array. for (String value : values) { // Call the trim method. String trimmed = value.trim(); // Display the strings. System.out.print("[" + trimmed + "]"); System.out.println("[" + value + "]"); } } }[cat][ cat] [dog][dog ] [=bird=][ =bird= ] [fish][fish ] [line][line ]
Trim
start, endThis program implements two custom methods. We use the replaceFirst
method to replace whitespace at the start or end of a string
. So we trim on just one side.
public class Program { public static String trimEnd(String value) { // Use replaceFirst to remove trailing spaces. return value.replaceFirst("\\s+$", ""); } public static String trimStart(String value) { // Remove leading spaces. return value.replaceFirst("^\\s+", ""); } public static void main(String[] args) { String value = " /Test? "; // Use custom trimEnd and trimStart methods. System.out.println("[" + trimEnd(value) + "]"); System.out.println("[" + trimStart(value) + "]"); } }[ /Test?] [/Test? ]^ The start of a string. \s+ One or more space characters. $ The end of a string.
Often, calling trim()
is unnecessary. If trim is used and it is not needed, removing it will make a program faster. This could cause a behavior change.
Sometimes we need to handle whitespace characters within strings, not just on their starts or ends. With regular expressions, or parsers, we condense or remove spaces.
In other languages, like Ruby or Perl, we invoke the chop and chomp methods. In Python we use strip()
to remove whitespace on starts and ends.
To summarize, various trimming methods are similar. When a file is read, and lines may have useless (or invalid) whitespace on the ends, these methods are needed. Trim()
is a simple and clear call.