How can I trim characters in Java?
e.g.
String j = “\joe\jill\”.Trim(new char[] {“\”});
j should be
"joe\jill"
String j = “jack\joe\jill\”.Trim("jack");
j should be
"\joe\jill\"
etc
Java String trim()The Java String class trim() method eliminates leading and trailing spaces. The Unicode value of space character is '\u0020'. The trim() method in Java string checks this Unicode value before and after the string, if it exists then the method removes the spaces and returns the omitted string.
trim() in Java removes all the leading and trailing spaces in the string. It does not take any parameter and returns a new string. The trim method checks for the Unicode value of the space and eliminates it. The trim() in Java does not remove middle spaces.
You can use Apache StringUtils. stripStart to trim leading characters, or StringUtils. stripEnd to trim trailing characters.
Trim() Removes all leading and trailing white-space characters from the current string.
Apache Commons has a great StringUtils class (org.apache.commons.lang.StringUtils). In StringUtils
there is a strip(String, String)
method that will do what you want.
I highly recommend using Apache Commons anyway, especially the Collections and Lang libraries.
This does what you want:
public static void main (String[] args) { String a = "\\joe\\jill\\"; String b = a.replaceAll("\\\\$", "").replaceAll("^\\\\", ""); System.out.println(b); }
The $
is used to remove the sequence in the end of string. The ^
is used to remove in the beggining.
As an alternative, you can use the syntax:
String b = a.replaceAll("\\\\$|^\\\\", "");
The |
means "or".
In case you want to trim other chars, just adapt the regex:
String b = a.replaceAll("y$|^x", ""); // will remove all the y from the end and x from the beggining
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