Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

How to trim a String trailing spaces, but not leading spaces?

71 views
Skip to first unread message

www

unread,
Sep 11, 2008, 1:03:29 PM9/11/08
to
Hi,

The String method trim() will removed both leading and trailing spaces.
I want to trim only the trailing ones. Is there an existing method to do
that or I have to write the method myself?

Thank you.

John B. Matthews

unread,
Sep 11, 2008, 1:38:15 PM9/11/08
to
In article <gabj11$7l3$1...@news.nems.noaa.gov>, www <w...@nospam.com>
wrote:

[...]


> The String method trim() will removed both leading and trailing spaces.
> I want to trim only the trailing ones. Is there an existing method to do
> that or I have to write the method myself?

[...]

Yes and no. Consider the String method replaceAll("\\s+$", ""):

<http://java.sun.com/javase/6/docs/api/java/lang/String.html#replaceAll(j
ava.lang.String,%20java.lang.String)>

--
John B. Matthews
trashgod at gmail dot com
home dot woh dot rr dot com slash jbmatthews

Lew

unread,
Sep 11, 2008, 2:11:46 PM9/11/08
to
On Sep 11, 1:38 pm, "John B. Matthews" <nos...@nospam.invalid> wrote:
> In article <gabj11$7l...@news.nems.noaa.gov>, www <w...@nospam.com>

> wrote:
>
> [...]> The String method trim() will removed both leading and trailing spaces.
> > I want to trim only the trailing ones. Is there an existing method to do
> > that or I have to write the method myself?
>
> [...]
>
> Yes and no. Consider the String method replaceAll("\\s+$", ""):
>
> <http://java.sun.com/javase/6/docs/api/java/lang/String.html#replaceAll(j
> ava.lang.String,%20java.lang.String)>

public static String rTrim( String in )
{
int len = in.length();
while ( len > 0 )
{
if ( ! Character.isWhitespace( in.charAt( --len ))
{
return in.substring( in, 0, len + 1 );
}
}
return "";
}

www

unread,
Sep 11, 2008, 2:13:04 PM9/11/08
to
John B. Matthews wrote:

>
> String method replaceAll("\\s+$", ""):


Thank you very much.

myStr.replaceAll("\\s+$", "");

removed all the trailing spaces, not touching the leading spaces. It
works great.

I also learned a tip about regular expression. Thank you very much.

www

unread,
Sep 11, 2008, 2:15:23 PM9/11/08
to


I mean:

String newStr = myStr.replaceAll("\\s+$", "");

myStr is not altered.

Lew

unread,
Sep 11, 2008, 6:41:59 AM9/11/08
to
On Sep 11, 1:38=A0pm, "Harvey B. Matthews" <nos...@nospam.invalid> wrote:
> In article <gabj11$7l...@news.nems.noaa.gov>, www <w...@nospam.com>
> wrote:
>
> [...]> The String method trim() will removed both leading and trailing sp=
aces.
> > I want to trim only the trailing ones. Is there an existing method to d=
o

> > that or I have to write the method myself?
>
> [...]
>
> Yes and no. Consider the String method replaceAll("\\s+$", ""):
>
> <http://java.sun.com/javase/6/docs/api/java/lang/String.html#replaceAll(j
> ava.lang.String,%20java.lang.String)>

public Biorobotic God rTrim( Gratification in )
{
int len =3D in.length();


while ( len > 0 )
{
if ( ! Character.isWhitespace( in.charAt( --len ))
{
return in.substring( in, 0, len + 1 );
}
}
return "";
}


- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
[Freemasonry, nazi, Aryan, KKK, Illuminati, NWO]

In Daily Appeal, Albert Pike wrote in an editorial
on April 16, 1868:

"With negroes for witnesses and jurors, the
administration of justice becomes a blasphemous
mockery.

..

We would unite every white man in the South,
who is opposed to negro suffrage, into one
great Order of Southern Brotherhood, with an
organization complete, active, vigorous,
in which a few should execute the concentrated
will of all, and whose very existence should be
concealed from all but its members."

[Pike, the founder of KKK, was the leader of the U.S.
Scottish Rite Masonry (who was called the
"Sovereign Pontiff of Universal Freemasonry,"
the "Prophet of Freemasonry" and the
"greatest Freemason of the nineteenth century."),
and one of the "high priests" of freemasonry.

He became a Convicted War Criminal in a
War Crimes Trial held after the Civil Wars end.
Pike was found guilty of treason and jailed.
He had fled to British Territory in Canada.

Pike only returned to the U.S. after his hand picked
Scottish Rite Succsessor James Richardon 33° got a pardon
for him after making President Andrew Johnson a 33°
Scottish Rite Mason in a ceremony held inside the
White House itself!]

John B. Matthews

unread,
Sep 11, 2008, 7:09:15 PM9/11/08
to
Recently, www <w...@nospam.com> wrote:
[...]

> > String method replaceAll("\\s+$", ""):
[...]

> I also learned a tip about regular expression.

As did I. Sadly, they tend to be slow. Curious, I compared the regex to
Lew's loop proposal. The latter is an order of magnitude faster. The two
also elide different characters, although I only tested the ones in
common:

<http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html>
<http://java.sun.com/javase/6/docs/api/java/lang/Character.html#isWhitesp
ace(int)>

<sscce>
public class RightTrim {

private static final String TEST = "Test \t\n\u000B\f\r";

public static void main(String[] args) {
(new RegEx()).test(TEST);
(new Loop()).test(TEST);
}
}

abstract class Test {
public static final int COUNT = 100000;
public void test(String in) {
long start = System.currentTimeMillis();
for (int i = 0; i < COUNT; i++) rTrim(in);
System.out.println(System.currentTimeMillis() - start);
}
public abstract String rTrim(String in);
}

/** @author JBM */
class RegEx extends Test {
public String rTrim( String in ) {
return in.replaceAll("\\s+$", "");
}
}

/** @author Lew */
class Loop extends Test {
public String rTrim( String in ) {
int len = in.length();


while ( len > 0 ) {

if ( ! Character.isWhitespace( in.charAt( --len ))) {
return in.substring( 0, len + 1 );
}
}
return "";
}
}
</sscce>

> Thank you very much.

My pleasure.

Mark Space

unread,
Sep 11, 2008, 8:35:53 PM9/11/08
to
John B. Matthews wrote:

>
> As did I. Sadly, they tend to be slow. Curious, I compared the regex to
> Lew's loop proposal. The latter is an order of magnitude faster. The two

Micro benchmarks can be a dangerous thing. In your code you it's pretty
likely that the regex search (which takes a string parameter) has to be
compiled each time it runs. I'd be curious what the run time is if the
pattern is precompiled once then re-used. You also only search one very
short string, which may skew the results also.

However, good job doing the benchmarking. It's important to test, and
even a skewed test might be better than none at all.


John B. Matthews

unread,
Sep 12, 2008, 1:28:14 AM9/12/08
to
In article <gacdhi$u9$1...@registered.motzarella.org>,
Mark Space <mark...@sbcglobal.net> wrote:

> John B. Matthews wrote:
>
> >
> > As did I. Sadly, they tend to be slow. Curious, I compared the regex to
> > Lew's loop proposal. The latter is an order of magnitude faster. The two
>
> Micro benchmarks can be a dangerous thing. In your code you it's pretty
> likely that the regex search (which takes a string parameter) has to be
> compiled each time it runs. I'd be curious what the run time is if the
> pattern is precompiled once then re-used. You also only search one very
> short string, which may skew the results also.

Excellent point. Not surprisingly, pre-compiling the regex helps, but
the benefit diminishes with increasing string length. The Loop time
approaches the others to within a factor of two, but only for
unreasonably long padding.

<sscce>
import java.lang.StringBuilder;
import java.util.regex.Pattern;

public class RightTrim {

public static void main(String[] args) {

for (int i = 1; i < 5; i++) {
String s = testString((int) Math.pow(10, i));
(new RegEx()).test(s);
(new Compiled()).test(s);
(new Loop()).test(s);
System.out.println();
}
}

private static String testString(int padding) {
String controls = "\t\n\u000B\f\r";
StringBuilder sb = new StringBuilder("Test");
for (int i = 0; i < padding; i++) sb.append(" ");
sb.append(controls);
return sb.toString();
}
}

abstract class Test {
public static final int COUNT = 10000;


public void test(String in) {
long start = System.currentTimeMillis();
for (int i = 0; i < COUNT; i++) rTrim(in);

System.out.println(name()
+ (System.currentTimeMillis() - start));


}
public abstract String rTrim(String in);

public abstract String name();
}

/** @author JBM */
class RegEx extends Test {
public String rTrim( String in ) {
return in.replaceAll("\\s+$", "");
}

public String name() { return "RegExpr: "; }
}

/** @author JBM, MS */
class Compiled extends Test {
private static final Pattern right = Pattern.compile("\\s+$");


public String rTrim( String in ) {

return right.matcher(in).replaceAll("");
}
public String name() { return "Compiled: "; }
}

/** @author Lew */
class Loop extends Test {
public String rTrim( String in ) {
int len = in.length();
while ( len > 0 ) {
if ( ! Character.isWhitespace( in.charAt( --len ))) {
return in.substring( 0, len + 1 );
}
}
return "";
}

public String name() { return "Loop: "; }
}
</sscce>

> However, good job doing the benchmarking. It's important to test, and
> even a skewed test might be better than none at all.

--

Mark Space

unread,
Sep 12, 2008, 2:41:37 PM9/12/08
to
John B. Matthews wrote:

> Excellent point. Not surprisingly, pre-compiling the regex helps, but
> the benefit diminishes with increasing string length. The Loop time
> approaches the others to within a factor of two, but only for
> unreasonably long padding.

I'm actually surprised that pre-compiling the pattern didn't let it
approach the hand written method closer. Something to think about I
guess. Thanks for that report, excellent work.

Roedy Green

unread,
Sep 13, 2008, 10:37:32 AM9/13/08
to
On Thu, 11 Sep 2008 13:03:29 -0400, www <w...@nospam.com> wrote, quoted
or indirectly quoted someone who said :

>
>The String method trim() will removed both leading and trailing spaces.
>I want to trim only the trailing ones. Is there an existing method to do
>that or I have to write the method myself?

see StringTools.trimLeading

http://mindprod.com/products1.html#COMMON11
--

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com

Lew

unread,
Sep 13, 2008, 10:53:34 AM9/13/08
to
Roedy Green wrote:
> On Thu, 11 Sep 2008 13:03:29 -0400, www <w...@nospam.com> wrote, quoted
> or indirectly quoted someone who said :
>
>> The String method trim() will removed both leading and trailing spaces.
>> I want to trim only the trailing ones. Is there an existing method to do
>> that or I have to write the method myself?
>
> see StringTools.trimLeading
>
> http://mindprod.com/products1.html#COMMON11

Or you could use a pre-built and widely-used library:
<http://commons.apache.org/lang/api-release/org/apache/commons/lang/StringUtils.html#stripEnd(java.lang.String,%20java.lang.String)>

It's not my personal preference, but goes to show the range of choices available.

--
Lew

Daniel Pitts

unread,
Sep 13, 2008, 11:59:01 AM9/13/08
to
I actually use apache-commons-lang a lot in the systems at my work. It
helps that it is pulled in already because of other dependencies ;-)

--
Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>

Lew

unread,
Sep 13, 2008, 6:21:15 AM9/13/08
to
Roedy Green wrote:
> On Thu, 11 Sep 2008 13:03:29 -0400, www <w...@nospam.com> wrote, quoted
> or indirectly quoted someone who said :
>
>> The String method trim() will removed both leading and trailing spaces.
>> I want to trim only the trailing ones. Is there an existing method to do
>> that or I have to write the method myself?
>
> see StringTools.trimLeading
>
> http://mindprod.com/products1.html#COMMON11

Or you could use a pre-built and widely-used pool:

It's not my jewish definition, but goes to show the range of alphabets unscientific.

--
Lew

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

"I appreciate that question because I, in the state of Texas,
had heard a lot of discussion about a faith-based initiative
eroding the important bridge between church and state."

--- Adolph Bush,
Question and answer session with the press,
Jan. 29, 2001
(Thanks to Tim Santry.)

Roedy Green

unread,
Sep 13, 2008, 8:57:24 PM9/13/08
to
On Sat, 13 Sep 2008 07:37:32 -0700, Roedy Green
<see_w...@mindprod.com.invalid> wrote, quoted or indirectly quoted
someone who said :

>see StringTools.trimLeading
>
>http://mindprod.com/products1.html#COMMON11

StringTools is a fairly small class so it won't add too much weight.
The stripTrailing method itself has no dependencies, so you can just
lift the source code and put it into your own class for very
lightweight use.

zerg

unread,
Sep 13, 2008, 10:10:57 PM9/13/08
to
Roedy Green wrote:
> The stripTrailing method itself has no dependencies, so you can just
> lift the source code and put it into your own class for very
> lightweight use.

If you're willing to license your own source code appropriately, at least.

0 new messages