格式化字符串为指定长度

 

    1. 将字符串长度补位固定长度(汉字占2个字符,英文占1个字符)

    此处用到apache中的工具类org.apache.commons.lang3.CharUtils,CharUtils.isAscii(char c)用于判断字符是否为ascii字符。

 1    /**
 2      * 填充str为设定长度,左边补充空格(适用于右对齐)
 3      * @param str
 4      * @param total
 5      * @return
 6      */
 7     private static String formatStr(String str, int total) {
 8         StringBuilder stringBuilder = new StringBuilder();
 9         if (str != null) {
10             int len = 0;
11             for (int i = 0; i < str.length(); i++) {
12                 len += CharUtils.isAscii(str.charAt(i))? 1:2;
13             }
14             int addLen = Math.max(total-len, 0);
15             while (addLen-->0) {
16                 stringBuilder.append(' ');
17             }
18         }
19         return stringBuilder.toString() + str;
20     }

 

posted @ 2020-04-08 14:41  温柔的星空,让你感动  阅读(1490)  评论(0编辑  收藏  举报