【记录】字符串固定位数中插入逗号

参数说明:
str:要插入逗号的字符串
index:插入的位数
如有需要也可将逗号转为其他字符串,也可作为参数传入

    public String insertCommaInStr(String str,int index){
        if (index<=0){
            return null;
        }
        //去除字符串中的\n和\t符号,头尾去空
        String string = str.replaceAll("\n|\t", "").trim();
        StringBuilder sb = new StringBuilder();
        sb.append(string);
        for (int i = sb.length()-index; i >0; i-=index) {
            sb.insert(i,",");
        }
        return sb.toString();
    }
posted @ 2022-08-15 16:41  植树chen  阅读(81)  评论(0编辑  收藏  举报