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
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
Apache Commons has a great StringUtils class (org.apache.commons.lang.StringUtils). In
StringUtils
there is astrip(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:
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:
The
|
means "or".In case you want to trim other chars, just adapt the regex:
it appears that there is no ready to use java api that makes that but you can write a method to do that for you. this link might be usefull
CharMatcher
– Google GuavaIn the past, I'd second Colins’ Apache commons-lang answer. But now that Google’s guava-libraries is released, the CharMatcher class will do what you want quite nicely:
CharMatcher has a very simple and powerful set of APIs as well as some predefined constants which make manipulation very easy. For example:
Very nice stuff.
Here is another non-regexp, non-super-awesome, non-super-optimized, however very easy to understand non-external-lib solution:
Usage:
Hand made for the first option:
Prints
joe\jil
joe\jil