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: Eric Sosman Newsgroups: comp.lang.java.programmer Subject: Re: how to trim() a String only at the right side? Date: Wed, 25 Sep 2013 10:25:08 -0400 Organization: A noiseless patient Spider Lines: 24 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Injection-Date: Wed, 25 Sep 2013 14:25:14 +0000 (UTC) Injection-Info: mx05.eternal-september.org; posting-host="0d73d8cc209bff1c6395088b400d0605"; logging-data="5584"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX19QPftZ99EzAiBY+9tixB8A" User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:17.0) Gecko/20130801 Thunderbird/17.0.8 In-Reply-To: Cancel-Lock: sha1:iSokHK0Rmws2pK1CRI9EWQU/Uwk= Xref: csiph.com comp.lang.java.programmer:25329 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