• Java字符串前用零补齐


    源程序代码

    
    private static final String FORMAT_STRING = "00000000";
    
    /**
     * 字符串前用零补齐
     *
     * @param src 原始字符串
     * @return 补齐后的字符串
     */
    public static String formatWithMakingUp(String src) {
        if (null == src) {
            return null;
        }
        int delta = FORMAT_STRING.length() - src.length();
        if (delta <= 0) {
            return src;
        }
        return FORMAT_STRING.substring(0, delta) + src;
    }
    

    测试用例

    /**
     * @author Yawei Xi
     */
    public class Test {
    
        private static final String FORMAT_STRING = "00000000";
    
        /**
         * 字符串前用零补齐
         *
         * @param src 原始字符串
         * @return 补齐后的字符串
         */
        public static String formatWithMakingUp(String src) {
            if (null == src) {
                return null;
            }
            int delta = FORMAT_STRING.length() - src.length();
            if (delta <= 0) {
                return src;
            }
            return FORMAT_STRING.substring(0, delta) + src;
        }
    
        public static void main(String[] args) {
            String a = "1";
            String b = "12";
            String c = "123";
            String d = "1234";
            String e = "12345";
            String f = "123456";
            String g = "1234567";
            String h = "12345678";
            String i = "123456789";
            System.out.println(formatWithMakingUp(a));
            System.out.println(formatWithMakingUp(b));
            System.out.println(formatWithMakingUp(c));
            System.out.println(formatWithMakingUp(d));
            System.out.println(formatWithMakingUp(e));
            System.out.println(formatWithMakingUp(f));
            System.out.println(formatWithMakingUp(g));
            System.out.println(formatWithMakingUp(h));
            System.out.println(formatWithMakingUp(i));
        }
    }
    

    输出结果

    00000001
    00000012
    00000123
    00001234
    00012345
    00123456
    01234567
    12345678
    123456789
    
  • 相关阅读:
    [单调栈] Jzoj P4260 最大子矩阵
    [前缀和] Jzoj P4259 矩形
    [欧拉回路][状压dp] Jzoj P3290 吃货JYY
    [组合数][枚举] Jzoj P3332 棋盘游戏
    [欧拉函数][dp][快速幂] Jzoj P1161 机器人M号
    [exgcd] Jzoj P1158 荒岛野人
    [带权并查集] Jzoj P1503 体育场
    [dfs][树的直径] Jzoj P1737 删边
    [差分][倍增lca][tarjan] Jzoj P3325 压力
    [dfs] Jzoj P1497 景点中心
  • 原文地址:https://www.cnblogs.com/freelancy/p/14860014.html
Copyright © 2020-2023  润新知