Trim characters in Java

Quintin Par picture Quintin Par · Jan 18, 2010 · Viewed 131k times · Source

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

Answer

Colin Gislason picture Colin Gislason · Jan 18, 2010

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.