how to trim() a String only at the right side?

A

Andreas Leitgeb

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
 
E

Eric Sosman

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

You could kill your canary with the regex cannon, I guess.
I'd just write the loop, maybe starting out with lastIndexOf(' ').

Some people, when confronted with a problem, think
"I know, I'll use regular expressions." Now they
have two problems.
-- Jamie Zawinski
 
J

John B. Matthews

Andreas Leitgeb said:
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

This example compares regex & loop approaches:

<https://groups.google.com/d/msg/comp.lang.java.programmer/KLCzPtBzm1c/fP-4nqBXTs8J>
 
J

Jim Janney

Andreas Leitgeb said:
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

public static CharSequence trimEnd(CharSequence s) {
return s.length() == 0 || s.charAt(s.length() - 1) != ' ' ? s :
trimEnd(s.subSequence(0, s.length() - 1));
}

No explicit loops, works on String and StringBuilder. :)

Also, Apache StringUtils has a stripEnd() method.
 
S

Silvio

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

String trimRight(String str)
{
return ("x" + str).trim().substring(1);
}
 
M

markspace

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.
 
M

markspace

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 );

I realized just after I posted that the last line should probably be

return cs.substring( 0, i+1 );
 
S

Silvio

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.
Elegant is a relative term and you did not state the need for an
efficient solution. I consider a short-and-simple solution elegant until
it has been proven too inefficient for the purpose of its application.

In all other circumstances this solution (apart from being incorrect)
reeks like premature optimization.
 
J

Jim Janney

markspace said:
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.

In older versions of Java where substring takes constant time, the time
for the recursive version would be proportional to the number of
trailing blanks: the main concern would probably be stack overflow. In
more recent implementations, where substring does an actual copy, it
could potentially take quadratic time--definitely not a good idea. I
agree that if speed is wanted a loop is the best approach. The
existence of the Apache util suggests that there isn't a good solution
in the JRE library.
 
A

Andreas Leitgeb

A summary of the answers so far is:
-) use regex: A while ago, I liked REs, but with many tools
using different dialects of it, my enthusiasm has declined.
Thanks, anyway, for suggesting it.

-) a recursive function: lol ;-)

-) prepend an "x", then trim() it, then remove the "x":
A nice&compact one, and I'm not yet in the phase for
performance-considerations, so I might actually start
out using it. That it eats not only blanks, but also
control chars will not be a real problem, until I get
to rewrite it. The strings I'm going to deal with are
unlikely to contain tabs or newlines, so if this ever
bites someone, that might be many years from now and
give a job to some future programmer to fix ;)

-) Use Apache Utils' StringUtils class: good to know, but
at this time it would be the first/only thing from that
library, so I'm reluctant to include a 3rd party library
for some code of maybe 3-4 lines (if done with a loop).

Thanks to *all* who answered. I'll now reread them all, and
eventually make specific followups to some.
 
A

Arne Vajhøj

In older versions of Java where substring takes constant time, the time
for the recursive version would be proportional to the number of
trailing blanks: the main concern would probably be stack overflow. In
more recent implementations, where substring does an actual copy, it
could potentially take quadratic time--definitely not a good idea. I
agree that if speed is wanted a loop is the best approach. The
existence of the Apache util suggests that there isn't a good solution
in the JRE library.

at the time Apache added that method.

Arne
 
A

Andreas Leitgeb

Well, I didn't ask for a ready-to-use implementation, but now,
as I got one, anyway, I'll probably be lazy and just use it.

I guess mine would have looked essentially the same.

Thanks for supporting my laziness ;-)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,955
Messages
2,570,117
Members
46,705
Latest member
v_darius

Latest Threads

Top