Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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. </p> <pre><code>public String trim( String stringToTrim, String stringToRemove ) { String answer = stringToTrim; while( answer.startsWith( stringToRemove ) ) { answer = answer.substring( stringToRemove.length() ); } while( answer.endsWith( stringToRemove ) ) { answer = answer.substring( 0, answer.length() - stringToRemove.length() ); } return answer; } </code></pre> <p>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.</p> <p>Some performance times for running each of the following 10 million times.</p> <p><code>" mile ".trim();</code> runs in 248 ms <em>included as a reference implementation for performance comparisons.</em></p> <p><code>trim( "smiles", "s" );</code> runs in 547 ms - approximately 2 times as long as java's <code>String.trim()</code> method.</p> <p><code>"smiles".replaceAll("s$|^s","");</code> runs in 12,306 ms - approximately 48 times as long as java's <code>String.trim()</code> method.</p> <p>And using a compiled regex pattern <code>Pattern pattern = Pattern.compile("s$|^s");</code> <code>pattern.matcher("smiles").replaceAll("");</code> runs in 7,804 ms - approximately 31 times as long as java's <code>String.trim()</code> method.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload