Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.java.programmer > #25327 > unrolled thread

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

Started byAndreas Leitgeb <avl@gamma.logic.tuwien.ac.at>
First post2013-09-25 13:55 +0000
Last post2013-09-26 16:56 +0000
Articles 14 — 8 participants

Back to article view | Back to comp.lang.java.programmer


Contents

  how to trim() a String only at the right side? Andreas Leitgeb <avl@gamma.logic.tuwien.ac.at> - 2013-09-25 13:55 +0000
    Re: how to trim() a String only at the right side? Eric Sosman <esosman@comcast-dot-net.invalid> - 2013-09-25 10:25 -0400
    Re: how to trim() a String only at the right side? "John B. Matthews" <nospam@nospam.invalid> - 2013-09-25 12:55 -0400
    Re: how to trim() a String only at the right side? Jim Janney <jjanney@shell.xmission.com> - 2013-09-25 13:05 -0600
    Re: how to trim() a String only at the right side? Silvio <silvio@internet.com> - 2013-09-25 21:46 +0200
    Re: how to trim() a String only at the right side? markspace <markspace@nospam.nospam> - 2013-09-25 13:31 -0700
      Re: how to trim() a String only at the right side? markspace <markspace@nospam.nospam> - 2013-09-25 13:41 -0700
        Re: how to trim() a String only at the right side? Andreas Leitgeb <avl@gamma.logic.tuwien.ac.at> - 2013-09-26 17:11 +0000
      Re: how to trim() a String only at the right side? Silvio <silvio@internet.com> - 2013-09-26 12:14 +0200
      Re: how to trim() a String only at the right side? Jim Janney <jjanney@shell.xmission.com> - 2013-09-26 09:44 -0600
        Re: how to trim() a String only at the right side? Arne Vajhøj <arne@vajhoej.dk> - 2013-09-26 13:01 -0400
    Re: how to trim() a String only at the right side? lipska the kat <"nospam at neversurrender dot co dot uk"> - 2013-09-26 12:21 +0100
      Re: how to trim() a String only at the right side? lipska the kat <"nospam at neversurrender dot co dot uk"> - 2013-09-26 17:40 +0100
    Re: how to trim() a String only at the right side? Andreas Leitgeb <avl@gamma.logic.tuwien.ac.at> - 2013-09-26 16:56 +0000

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

FromAndreas Leitgeb <avl@gamma.logic.tuwien.ac.at>
Date2013-09-25 13:55 +0000
Subjecthow to trim() a String only at the right side?
Message-ID<slrnl45qr1.mol.avl@gamma.logic.tuwien.ac.at>
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

[toc] | [next] | [standalone]


#25329

FromEric Sosman <esosman@comcast-dot-net.invalid>
Date2013-09-25 10:25 -0400
Message-ID<l1uroa$5eg$1@dont-email.me>
In reply to#25327
On 9/25/2013 9: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

     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

-- 
Eric Sosman
esosman@comcast-dot-net.invalid

[toc] | [prev] | [next] | [standalone]


#25330

From"John B. Matthews" <nospam@nospam.invalid>
Date2013-09-25 12:55 -0400
Message-ID<nospam-47DC05.12550725092013@news.aioe.org>
In reply to#25327
In article <slrnl45qr1.mol.avl@gamma.logic.tuwien.ac.at>,
 Andreas Leitgeb <avl@gamma.logic.tuwien.ac.at> 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

This example compares regex & loop approaches:

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

-- 
John B. Matthews
trashgod at gmail dot com
<http://sites.google.com/site/drjohnbmatthews>

[toc] | [prev] | [next] | [standalone]


#25334

FromJim Janney <jjanney@shell.xmission.com>
Date2013-09-25 13:05 -0600
Message-ID<ydn8uykoh6y.fsf@shell.xmission.com>
In reply to#25327
Andreas Leitgeb <avl@gamma.logic.tuwien.ac.at> writes:

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

-- 
Jim Janney

[toc] | [prev] | [next] | [standalone]


#25335

FromSilvio <silvio@internet.com>
Date2013-09-25 21:46 +0200
Message-ID<52433d82$0$16000$e4fe514c@news2.news.xs4all.nl>
In reply to#25327
On 09/25/2013 03:55 PM, 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
>

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

[toc] | [prev] | [next] | [standalone]


#25338

Frommarkspace <markspace@nospam.nospam>
Date2013-09-25 13:31 -0700
Message-ID<l1vh7v$bjh$1@dont-email.me>
In reply to#25327
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.



[toc] | [prev] | [next] | [standalone]


#25339

Frommarkspace <markspace@nospam.nospam>
Date2013-09-25 13:41 -0700
Message-ID<l1vhpg$ehn$1@dont-email.me>
In reply to#25338
On 9/25/2013 1:31 PM, markspace wrote:

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

[toc] | [prev] | [next] | [standalone]


#25359

FromAndreas Leitgeb <avl@gamma.logic.tuwien.ac.at>
Date2013-09-26 17:11 +0000
Message-ID<slrnl48qmb.mol.avl@gamma.logic.tuwien.ac.at>
In reply to#25339
markspace <markspace@nospam.nospam> wrote:
>>    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+1 );
>>    }

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

[toc] | [prev] | [next] | [standalone]


#25347

FromSilvio <silvio@internet.com>
Date2013-09-26 12:14 +0200
Message-ID<52440900$0$16003$e4fe514c@news.xs4all.nl>
In reply to#25338
On 09/25/2013 10:31 PM, markspace wrote:
> 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. 
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.

[toc] | [prev] | [next] | [standalone]


#25350

FromJim Janney <jjanney@shell.xmission.com>
Date2013-09-26 09:44 -0600
Message-ID<ydn4n97oae1.fsf@shell.xmission.com>
In reply to#25338
markspace <markspace@nospam.nospam> writes:

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

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.

-- 
Jim Janney

[toc] | [prev] | [next] | [standalone]


#25358

FromArne Vajhøj <arne@vajhoej.dk>
Date2013-09-26 13:01 -0400
Message-ID<5244686e$0$297$14726298@news.sunsite.dk>
In reply to#25350
On 9/26/2013 11:44 AM, Jim Janney wrote:
> markspace <markspace@nospam.nospam> writes:
>> 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.
>
> 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

[toc] | [prev] | [next] | [standalone]


#25348

Fromlipska the kat <"nospam at neversurrender dot co dot uk">
Date2013-09-26 12:21 +0100
Message-ID<P6adnQikdc5ehdnPnZ2dnUVZ8smdnZ2d@bt.com>
In reply to#25327
On 25/09/13 14:55, 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
>

package cljp;

import org.apache.commons.lang3.StringUtils;

public class Stripper {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String foo = "   foo   ";
		String bar = "bar";
		
		System.out.print(foo);
		System.out.println(bar);
		
		foo = StringUtils.stripEnd(foo, " ");
		
		System.out.print(foo);
		System.out.println(bar);

	}

}

-- 
Lipska the Kat©: Troll hunter, sandbox destroyer
and farscape dreamer of Aeryn Sun
GNU/Linux user #560883 - http://www.linuxcounter.net

[toc] | [prev] | [next] | [standalone]


#25355

Fromlipska the kat <"nospam at neversurrender dot co dot uk">
Date2013-09-26 17:40 +0100
Message-ID<q7adnXg0rtEA_tnPnZ2dnUVZ8lmdnZ2d@bt.com>
In reply to#25348
On 26/09/13 12:21, lipska the kat wrote:
> On 25/09/13 14:55, 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
>>
>
> package cljp;
>
> import org.apache.commons.lang3.StringUtils;
>
> public class Stripper {
>
>      /**
>       * @param args
>       */
>      public static void main(String[] args) {
>          String foo = "   foo   ";
>          String bar = "bar";
>
>          System.out.print(foo);
>          System.out.println(bar);
>
>          foo = StringUtils.stripEnd(foo, " ");
>
>          System.out.print(foo);
>          System.out.println(bar);
>
>      }
>
> }
>

Just FYI the apache commons StringUtils.stripEnd method employs while 
loops to get the work done.


lipska

-- 
Lipska the Kat©: Troll hunter, sandbox destroyer
and farscape dreamer of Aeryn Sun
GNU/Linux user #560883 - http://www.linuxcounter.net

[toc] | [prev] | [next] | [standalone]


#25356

FromAndreas Leitgeb <avl@gamma.logic.tuwien.ac.at>
Date2013-09-26 16:56 +0000
Message-ID<slrnl48pq1.mol.avl@gamma.logic.tuwien.ac.at>
In reply to#25327
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.

Andreas Leitgeb <avl@gamma.logic.tuwien.ac.at> 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.
> ...

[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.java.programmer


csiph-web