Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!eu.feeder.erje.net!eternal-september.org!feeder.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Jim Janney Newsgroups: comp.lang.java.programmer Subject: Re: how to trim() a String only at the right side? Date: Thu, 26 Sep 2013 09:44:38 -0600 Organization: bilaterally symmetric Lines: 33 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Info: mx05.eternal-september.org; posting-host="c75a2e3068ccf6c98395286f3e40b97d"; logging-data="22916"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/Sfdn/F4LKD+tG0qTuYBkH" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/23.3 (gnu/linux) Cancel-Lock: sha1:5sKmhKA5/0tuXGNQ6d0saCu1M40= sha1:u8Xl7RiP5YKLCj4B6YniBFwtK5I= Xref: csiph.com comp.lang.java.programmer:25350 markspace 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