views:

346

answers:

3
+4  Q: 

TrimEnd for Java?

In the process of converting a C# application to Java, I came across the use of String's TrimEnd method. Is there an equivalent Java implementation? I can't seem to find one.

I'd rather not replace it with trim, since I don't want to change the meaning or operation of the program at this point unless I have to.

+2  A: 

Here is a trick to do it from: http://www.overclock.net/coding-programming/320937-simple-java-trim-help.html

str = str.replaceAll(" +$", "");
Jon
Note this trims trailing spaces. @Paul Wagland's variation trims trailing whitespace characters. The C# method uses an array of "trimChars".
Jim Ferrans
That's true, +1 to Paul.
Jon
+3  A: 

There isn't a direct replacement. You can use regexps, or perhaps Commons Lang StringUtils.stripEnd() method.

Brian Agnew
+1 for StringUtils. In addition to trimXXX, they also offer stripXXX, which properly handles Unicode whitespace (trim only/also trims ASCII control codes).
Thilo
+8  A: 

There is no direct equivalent, however if you want to strip trailing whitespace you can use:

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

\s is the regular expression character set "whitespace", if you only care about stripping trailing spaces, you can replace it with the space character. If you want to use the more general form of trimEnd(), that is to remove an arbitrary set of trailing characters then you need to modify it slightly to use:

"string".replaceAll("[" + characters + "]+$", "");

Do be aware that the first argument is a generic regex, and so if one of your characters is the ] then this needs to be the first character in your list. For a full description of the java regex patterns, look at the javadoc.

Should you ever need to implement the trimstart() method from .net, it is almost the same, but would look like this:

"string".replaceAll("^[" + characters + "]+", "");
Paul Wagland
@finnw: You are correct… the regex needs to be anchored. Thanks for catching that for me, I have updated the answer to put in the correct regex.
Paul Wagland
Sorry it took me so long to get back to this. Thanks for the great answer! I just had to make one small correction. '"\s+$"' needs an extra '`' to properly escape it.
jasonh
@jasonh: You are correct, I have updated the answer, thanks.
Paul Wagland