On 9/25/2013 6:55 AM, Andreas Leitgeb wrote:
I'd need to trim only *trailing* whitespace off a String (or
StringBuilder)
while preserving leading white space. Furthermore (unlike trim()), I'd
only
strip exact \u0020 chars, no other control chars.
I could code a while-loop to search for last non-\u0020 char position
and then
extract the approriate substring (or delete() the spaces), but if
there is a
more elegant solution that I've missed in the javadocs, then I'd be
glad about
a hint.
PS: no need to code out any solutions involving explicit loops.
PPS: target is Java SE 7
Other than download some Apache string utils, I don't think there is
anything better than just using a loop. Most of the examples here were
fairly in efficient: extra concatenation or recursion are going to be
less efficient, potentially *a lot* less efficient.
The only thing I'd add would be an explicit test to see if you need to
bother or not (which could be a micro-optimization), and maybe consider
CharSequence instead of just String.
public CharSequence rTrim( CharSequence cs ) {
if( cs == null ) return null;
if( cs.length() == 0 || cs.charAt( cs.length()-1 ) != ' ' )
return cs;
int i = cs.length()-1;
while( i >= 0 && cs.charAt( i ) == ' ' ) i--;
return cs.substring( 0, i );
}
Not compiled or tested.
You called for an elegant solution and explicitly excluded loops.
efficient solution. I consider a short-and-simple solution elegant until
it has been proven too inefficient for the purpose of its application.