`

java string.format()

    博客分类:
  • Java
阅读更多

 

public static void main(String[] args)throws Exception {
        String s1 = "汉字";
        byte[] buff = s1.getBytes("GBK");
        System.out.println(buff.length);//4,汉字在GBK里面刚好是4个字节。
        String tmp = new String(buff,"ISO-8859-1");//把4个字节的字节数组按ISO方式转化成字符串
        System.out.println(tmp.length());//4,ISO里面一个字节就是一个字符,因此生成的字符串的长度是4
        System.out.println(tmp);//这里输出是乱码,是因为ISO编码里面并不包含汉字,转化不过来。
        String s2 = String.format("%6s",tmp);//格式化成6个长度,需要添加2个空格
        s2 = new String(s2.getBytes("ISO-8859-1"),"GBK");//先按ISO的方式还原出字节数组来,然后再按GBK编码成字符串。
        System.out.println(s2);//这里正常输出
    }
 

 

总的格式是:

 

%[argument_index$][flags][width][.precision]conversion

 

例如:
%2$-5.2s
//2$:取第二个参数
//-: 指定为左对齐,默认右对齐
//5:最大输出宽度为20,不够会补空格,实际若超过则全部输出
//.2:在此表示输出参数2的最大字符数量,如果是浮点数字,则表示小数部分显示的位数
//s :表示输入参数是字符串

 

 

  1. System.out.print(String.format("%1$-5s", result[i])); 
  2.  
  3. 结果: 
  4. 2    3    5    7    11   13   17   19   23   29    
  5. 31   37   41   43   47   53   59   61   67   71    
  6. 73   79   83   89   97   101  103  107  109  113   
  7. 127  131  137  139  149  151  157  163  167  173   
  8. 179  181  191  193  197  199  211  223  227  229   

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics