字符串补0操做

代码以下:ide

public static void main(String[] args) {
    System.out.println(addZeroForLeft(1001, 6));
    System.out.println(addZeroForLeft("abcd", 6));
}

/**
 * @描述: 整数前面补0
 * @param number 原始整数
 * @param formatLength 指定要格式化的长度
 * @return 补0后的字符串
 */
private static String addZeroForLeft(int number, int formatLength) {
    // 补0操做
    return String.format("%0" + formatLength + "d", number);
}

/**
 * @描述: 字符串前面补0
 * @param str 原始字符串
 * @param formatLength 指定要格式化的长度
 * @return 补0后的字符串
 */
private static String addZeroForLeft(String str, int formatLength) {
    int strLength = str.length();
    if (formatLength > strLength) {
        // 计算实际须要补0长度
        formatLength -= strLength;
        // 补0操做
        str = String.format("%0" + formatLength + "d", 0)   + str;
    }
    return str;
}

效果以下:code

001001
00abcd
相关文章
相关标签/搜索