C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Trim: 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.
Java program that uses trim method
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 + "]");
}
}
}
Output
[cat][ cat]
[dog][dog ]
[=bird=][ =bird= ]
[fish][fish ]
[line][line
]
Pattern: The "\s" sequence means "whitespace character" and "\\s+" is an escaped sequence. It means one or more whitespace characters.
Java program that trims starts and ends
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) + "]");
}
}
Output
[ /Test?]
[/Test? ]
Pattern
^ The start of a string.
\s+ One or more space characters.
$ The end of a string.
Caution: More than anything else, I have found performance improvements to cause program bugs.