public class stringFormat {
    public static void main (String args[]){
        String string = "10000";
        String st="计算机网络";
          System.out.print(String.format("%-20s", string));
          System.out.println("hello world !");
          System.out.print(String.format("%-20s", st ));
          System.out.print("hello world!");
        
       
    }
}我要其能对齐输出,该怎么做呢?

解决方案 »

  1.   

    %-20s 表示最少20个字符, 如果不到20个字符就补齐. 你可以看到hello world!后面应该有几个空格.
      

  2.   

    public class stringFormat {
        public static void main (String args[]){
            String string = "10000";
            String st="计算机网络";
              System.out.print(String.format("%-20s\t\t", string));
              System.out.println("hello world !");
              System.out.print(String.format("%-20s\t", st ));
              System.out.print("hello world!");
            
           
        }
    }
      

  3.   

    因为在 Java 中汉字和英文字符都属于一个 Unicode 字符,对于 %-20s 来说,
    只是占 20 个 Unicode 字符,对于 Java 来说汉字是算一个字符的。如果带有汉字的话,就不能采用这种方式来进行输出。
    public class Test {    public static void main(String[] arguments) {
            String string = "10000";
            String st="计算机网络";
            System.out.print(putString(string, 20, true));
            System.out.println("hello world !");
            System.out.print(putString(st, 20, true));
            System.out.print("hello world!");
        }
            /**
         * 输出指定宽度的字符串
          *
         * @param str       需要输出的原字符串
          * @param totalLen  字符串的占位宽度(以半角宽度计算)
          * @param isLeft    原字符串是否左对齐,true 左对齐,false 右对齐
          * return
         */
        public static String putString(String str, int totalLen, boolean isLeft) {
            int len = getLength(str);
            int diff = totalLen - len;
            String space = diff > 0 ? generateManyChar(' ', diff) : "";
            if(isLeft) {
                return str + space;
            }
            return space + str;        
        }    /**
         * 生成多个字符
          * @param c 需要生成的字符
          * @param length 字符的个数
          * @return length个字符组成的字符串
          */
        private static String generateManyChar(char c, int length) {
            if(length <= 0) {
                return "";
            }
            char[] chs = new char[length];
            for(int i = 0; i < length; i++) {
                chs[i] = c;
            }
            return new String(chs);
        }       /**
         * 获得一个字符串的长度,汉字算两个长度
          * @param str
         * @return 字符串的长度
          */
        private static int getLength(String str) {
            int length = 0;
            char[] c = str.toCharArray();
            for(int i = 0, k = c.length; i < k; i++) {
                if(c[i] <= 0xff) {
                    length++;
                }else{
                    length += 2;
                }
            }
            return length;
        }
    }