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
I don't think there is any built in function to trim based on a passed in string. Here is a small example of how to do this. This is not likely the most efficient solution, but it is probably fast enough for most situations, evaluate and adapt to your needs. I recommend testing performance and optimizing as needed for any code snippet that will be used regularly. Below, I've included some timing information as an example.
This answer assumes that the characters to be trimmed are a string. For example, passing in "abc" will trim out "abc" but not "bbc" or "cba", etc.
Some performance times for running each of the following 10 million times.
" mile ".trim();
runs in 248 ms included as a reference implementation for performance comparisons.trim( "smiles", "s" );
runs in 547 ms - approximately 2 times as long as java'sString.trim()
method."smiles".replaceAll("s$|^s","");
runs in 12,306 ms - approximately 48 times as long as java'sString.trim()
method.And using a compiled regex pattern
Pattern pattern = Pattern.compile("s$|^s");
pattern.matcher("smiles").replaceAll("");
runs in 7,804 ms - approximately 31 times as long as java'sString.trim()
method.Here's how I would do it.
I think it's about as efficient as it reasonably can be. It optimizes the single character case and avoids creating multiple substrings for each subsequence removed.
Note that the corner case of passing an empty string to trim is handled (some of the other answers would go into an infinite loop).
EDIT: Amended by answer to replace just the first and last '\' character.
You could use
removeStart
andremoveEnd
from Apache Commons Lang StringUtils10 year old question but felt most of the answers were a bit convoluted or didn't quite work the way that was asked. Also the most upvoted answer here didn't provide any examples. Here's a simple class I made:
https://gist.github.com/Maxdw/d71afd11db2df4f1297ad3722d6392ec
Usage: