Search code examples
javastringtrim

Trim characters in Java


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


Solution

  • 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.