Java strings can accumulate trailing whitespace from sources such as user input or file I/O. This excess whitespace can lead to logical errors in programs or degrade user experience. The standard String.trim() method removes whitespace from both ends of a string. To specifically target trailing whitespace, alternative approaches are necessary.
Iterative Character Examination
A manual approach involves iterating from the end of the string to find the last non-whitespace character.
public class WhitespaceTrimmer {
public static String stripTrailingWhitespace(String input) {
int index = input.length() - 1;
while (index >= 0 && Character.isWhitespace(input.charAt(index))) {
index--;
}
return input.substring(0, index + 1);
}
public static void main(String[] args) {
String text = "Sample Text ";
System.out.println("Original: '" + text + "'");
text = stripTrailingWhitespace(text);
System.out.println("Trimmed: '" + text + "'");
}
}
The stripTrailingWhitespace method starts at the last character index. It decrements the index while the character at that position is whitespace, as determined by Character.isWhitespace(). The method then returns the substring from the start to the identified index (inclusive).
Utilizing Regular Expressions
Java's regex capabilities provide a concise method for removing trailing whitespace.
public class RegexWhitespaceHandler {
public static String removeEndingWhitespace(String input) {
return input.replaceFirst("\\s+$", "");
}
public static void main(String[] args) {
String data = "Data Entry \t\n";
System.out.println("Before: '" + data + "'");
data = removeEndingWhitespace(data);
System.out.println("After: '" + data + "'");
}
}
The removeEndingWhitespace method uses String.replaceFirst() with the regex pattern "\\s+$". The pattern \\s matches any whitespace character, and $ anchors the match to the end of the string, ensuring only trailing whitespace is removed. Note that replaceAll would also work but is less semantically precise for a single trailing match.