Вот как бы я это сделал.
Я думаю, что это настолько эффективно, насколько это возможно. Он оптимизирует регистр одного символа и избегает создания нескольких подстрок для каждой удаленной подпоследовательности.
Обратите внимание, что обрабатывается угловой случай передачи пустой строки в обрезку (некоторые другие ответы будут идти в бесконечный цикл).
/** Trim all occurrences of the string <code>rmvval</code> from the left and right of <code>src</code>. Note that <code>rmvval</code> constitutes an entire string which must match using <code>String.startsWith</code> and <code>String.endsWith</code>. */
static public String trim(String src, String rmvval) {
return trim(src,rmvval,rmvval,true);
}
/** Trim all occurrences of the string <code>lftval</code> from the left and <code>rgtval</code> from the right of <code>src</code>. Note that the values to remove constitute strings which must match using <code>String.startsWith</code> and <code>String.endsWith</code>. */
static public String trim(String src, String lftval, String rgtval, boolean igncas) {
int str=0,end=src.length();
if(lftval.length()==1) { // optimize for common use - trimming a single character from left
char chr=lftval.charAt(0);
while(str<end && src.charAt(str)==chr) { str++; }
}
else if(lftval.length()>1) { // handle repeated removal of a specific character sequence from left
int vallen=lftval.length(),newstr;
while((newstr=(str+vallen))<=end && src.regionMatches(igncas,str,lftval,0,vallen)) { str=newstr; }
}
if(rgtval.length()==1) { // optimize for common use - trimming a single character from right
char chr=rgtval.charAt(0);
while(str<end && src.charAt(end-1)==chr) { end--; }
}
else if(rgtval.length()>1) { // handle repeated removal of a specific character sequence from right
int vallen=rgtval.length(),newend;
while(str<=(newend=(end-vallen)) && src.regionMatches(igncas,newend,rgtval,0,vallen)) { end=newend; }
}
if(str!=0 || end!=src.length()) {
if(str<end) { src=src.substring(str,end); } // str is inclusive, end is exclusive
else { src=""; }
}
return src;
}