GBK格式字符串右补空格

public class Test2 {
   public static void main(String[] s) throws IOException { 
  List<User> list = new ArrayList<User>();
    String aa = "";
  try {
    System.out.println(formatStr("汪333,3", 20));
   
  } catch (Exception e) {
   e.printStackTrace();
  }
   }
  
   
   /**
    * 补充空格
    * 参数(str字符串,字段的长度)
    */
  public static String formatStr(String str, int length) throws Exception {
     if (str == null) {
     return null;
     }
     int strLen = str.getBytes("GBK").length;  //空格的长度 = 20 - 字段的长度(GBK)。
     if (strLen == length) {
     return str;
     } else if (strLen < length) {
     int temp = length - strLen;
     String tem = "";
     for (int i = 0; i < temp; i++) {
     tem = tem + " ";
     }
     return str + tem;
     }else{
     return str.substring(0,length);
     }

    }

转载:https://blog.csdn.net/changNet/article/details/8674348?locationNum=13&fps=1

猜你喜欢

转载自www.cnblogs.com/ynyhl/p/9269821.html