Nice answer @Christine. I wrote a similar function to remove trailing whitespace from a CharSequence this afternoon:
/** Trims trailing whitespace. Removes any of these characters:
* 0009, HORIZONTAL TABULATION
* 000A, LINE FEED
* 000B, VERTICAL TABULATION
* 000C, FORM FEED
* 000D, CARRIAGE RETURN
* 001C, FILE SEPARATOR
* 001D, GROUP SEPARATOR
* 001E, RECORD SEPARATOR
* 001F, UNIT SEPARATOR
* @return "" if source is null, otherwise string with all trailing whitespace removed
*/
public static CharSequence trimTrailingWhitespace(CharSequence source) {
if(source == null)
return "";
int i = source.length();
// loop back to the first non-whitespace character
while(--i >= 0 && Character.isWhitespace(source.charAt(i))) {
}
return source.subSequence(0, i+1);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…