Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TrimEnd for Java?

Tags:

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.

like image 969
jasonh Avatar asked Jan 27 '10 00:01

jasonh


People also ask

What is the use of trim () in Java?

Java String trim() Method The trim() method removes whitespace from both ends of a string. Note: This method does not change the original string.

How do you right trim in Java?

We can use of String class replaceAll() method to implement left and right trim in Java. The replaceAll() method takes a regular expression and replaces each substring of this string that matches the regex with the specified replacement.

How do you trim a space in Java?

To remove leading and trailing spaces in Java, use the trim() method. This method returns a copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.

How Use trim and split in Java?

To remove extra spaces before and/or after the delimiter, we can perform split and trim using regex: String[] splitted = input. trim(). split("\\s*,\\s*");


2 Answers

Since Java 11, you can use "string".stripTrailing() to strip off trailing whitespace, or "string".stripLeading(). If you need the more generic version that strips off the specified characters, then see below, there is no direct replacement in Java 11.

Leaving the old answer here for pre-Java 11 versions:

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 + "]+", "");
like image 145
Paul Wagland Avatar answered Oct 01 '22 12:10

Paul Wagland


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

like image 29
Brian Agnew Avatar answered Oct 01 '22 11:10

Brian Agnew