java-替換字符串中花括號中的值(模仿log.info)


public static String replace(String msg,Object...params) {
        if(msg==null){
            throw new NullPointerException("msg");
        }
        StringBuffer sb=new StringBuffer();
        //定界符
        final String delimiter="{}";
        //括號出現的計數值
        int cnt=0;
        if(params!=null && params.length>0 ) {
            for(int i=0 ; i<=params.length ; i++) {
                int tmpIndex = msg.indexOf(delimiter);
                //不存在賦值
                if(tmpIndex == -1) {
                    if(cnt == 0 || StringUtils.isNotBlank(msg)) {
                        sb.append(msg);
                    }
                    break;
                }else {
                    //存在則進行賦值拼接
                    String str = msg.substring(0, tmpIndex);
                    msg = msg.substring((tmpIndex+2), msg.length());
                    String valStr = params[i].toString();
                    sb.append(str).append(valStr);
                    cnt++;

                }
            }
        }else {//param為空時
            sb.append(msg);
        }
        return sb.toString();
    }

  

測試:

public static void main(String[] args) {
        String csd = replace("新媒體{}文章嚴重錯敏詞{}通知:{}" ,"aa","bb","cc");
        System.out.println(csd);

    }

  

結果:

新媒體aa文章嚴重錯敏詞bb通知:cc

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM