JAVA去掉字符串左右两边的自定义字符

参考JDK String 类的 trim 方法实现

import javax.validation.constraints.NotNull;
import org.apache.commons.lang3.ArrayUtils;

public static String replaceCustomCharacter(@NotNull String str,@NotNull char... chars){
	    char[] val = str.toCharArray();
	    int st = 0 , len = val.length;
	    while ((st < len) && (ArrayUtils.contains(chars, val[st]))) {
	        st++;
	    }
	    while ((st < len) && (ArrayUtils.contains(chars, val[len - 1]))) {
	        len--;
	    }
	    return ((st > 0) || (len < val.length)) ? str.substring(st, len) : str;
	}
	
	public static void main(String[] args) {
		String str = " \t \n \r & replaceCustomCharacter  \t \n \r";
		char[] chars = new char[]{' ','\t','\n','\r','&'};
		str = replaceCustomCharacter(str, chars);
		String tab = "||||";
		System.out.println(tab.concat(str).concat(tab));
		
	}

console:

||||replaceCustomCharacter||||

你可能感兴趣的:(java,字符串)