Browse Source

打印字符串补全

xujunwei 1 year ago
parent
commit
5a3ab56006

+ 46 - 0
framework-common/src/main/java/com/mrxu/framework/common/util/StrFunc.java

@@ -1,5 +1,6 @@
 package com.mrxu.framework.common.util;
 
+import cn.hutool.core.util.StrUtil;
 import net.sourceforge.pinyin4j.PinyinHelper;
 import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
 import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
@@ -204,4 +205,49 @@ public class StrFunc {
         return url.toString();
     }
 
+    /**
+     * 打印字符串补全
+     * @param str
+     * @param length
+     * @return
+     */
+    public static String subPrinter(String str,int length) {
+        StringBuilder rs = new StringBuilder();
+        if(StrUtil.isBlank(str)) {
+            for(int i=0;i<=length;i++) {
+                rs.append(" ");
+            }
+            return rs.toString();
+        }
+        int calLength = 0;
+        int lastIndex = 0;
+        int lastTempLength = 0;
+        for(int i=0;i<str.length();i++) {
+            byte[] bytes = str.substring(i,i+1).getBytes();
+            lastTempLength = bytes.length;
+            lastTempLength = (lastTempLength>2)?2:lastTempLength;
+            calLength += lastTempLength;
+            if(calLength>length) {
+                lastIndex = i;
+                break;
+            }
+        }
+        if(calLength <= length) {
+            rs.append(str);
+            for(int i=0;i<=length-calLength;i++) {
+                rs.append(" ");
+            }
+        }
+        else {
+            rs.append(str.substring(0,lastIndex-1));
+            calLength -= lastTempLength;
+            calLength += 3;
+            rs.append("...");
+            for(int i=0;i<=length-calLength;i++) {
+                rs.append(" ");
+            }
+        }
+        return rs.toString();
+    }
+
 }