Java字符串格式化长度不足补0

当需要对字符串限定长度,而长度不够时在其前面或后面补充0。下面的代码是在前面补0,注释的哪行代码是在后面补0,根据实际情况选择:

package com.zxh.util;

public class StringUtil {

    //字符串格式化长度不足补0
    public static String addZeroForNum(String str, int strLength) {
        int strLen = str.length();
        if (strLen < strLength) {
            while (strLen < strLength) {
                StringBuffer sb = new StringBuffer();
                sb.append("0").append(str);// 左补0
                // sb.append(str).append("0");//右补0
                str = sb.toString();
                strLen = str.length();
            }
        }
        return str;
    }

}

需要传入字符串和限定的长度。

posted @ 2021-10-27 19:32  钟小嘿  阅读(3043)  评论(0编辑  收藏  举报