去除字符串首尾指定字符

/**
     * 去除字符串首尾出现的某个字符.
     *
     * @param source  源字符串.
     * @param element 需要去除的字符.
     * @return String.
     */
    public static  String trimFirstAndLastChar(String source, String element) {
        if(source==null){
            return "";
        }
        source = source.trim(); // 循环去掉字符串首的beTrim字符
        if(source.isEmpty()){
            return "";
        }
        String beginChar = source.substring(0, 1);
        if (beginChar.equalsIgnoreCase(element)) {
            source = source.substring(1, source.length());
        }
        // 循环去掉字符串尾的beTrim字符
        String endChar = source.substring(source.length() - 1, source.length());
        if (endChar.equalsIgnoreCase(element) && source.length()>1) {
            source = source.substring(0, source.length() - 1);
        }else{
            source = "";
        }
        return source;
    }

猜你喜欢

转载自blog.csdn.net/w522301629/article/details/81327687