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 trim, 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.
Detail This method is called on the string to be trimmed, which must not be null. It returns a new, modified string.
Tip We must assign the result of 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, end. This 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.
Detail The "\s" sequence means "whitespace character" and "\\s+" is an escaped sequence. It means one or more whitespace characters.
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.
Performance. 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.
Whitespace. 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.
Chop, chomp and strip. 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.
These 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 26, 2021 (edit link).