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.
Java String trim() Method The trim() method removes whitespace from both ends of a string. Note: This method does not change the original string.
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.
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.
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*");
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 + "]+", "");
There isn't a direct replacement. You can use regexps, or perhaps Commons Lang StringUtils.stripEnd() method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With