Path: csiph.com!usenet.pasdenom.info!aioe.org!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: Wed, 25 Sep 2013 13:05:25 -0600 Organization: bilaterally symmetric Lines: 25 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="11043"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/jzIKxZvWGrRhQnLUqge8h" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/23.3 (gnu/linux) Cancel-Lock: sha1:FbVPxSG/dJNvbiOwcxZUFwDprAs= sha1:92hB2fwWqsaXDtsM6Vf97SbJ4ys= Xref: csiph.com comp.lang.java.programmer:25334 Andreas Leitgeb 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