如果一个字符串长度规定为20 
在里面从左往右填充字符 不够20个则用空格补满 最简单的代码和最高效的代码分别是?
如果需求变为空格在字符串左边填充又如何实现?
谢谢!

解决方案 »

  1.   

    简单的话,这样行不行
    字符串a+“20空格” 然后substring
      

  2.   

    用20-已有长度,得到要添加空格数
    然后通过StringBuffer来循环添加
      

  3.   

    public class Test { public static void main(String[] args) {
    String str="123";
    System.out.println("右补空:["+String.format("%1$-20s", str)+"]");
    System.out.println("左补空:["+String.format("%1$20s", str)+"]"); }}
      

  4.   

    请问有关于format字符串的说明吗?很有用的样子
      

  5.   

    // Explicit argument indices may be used to re-order output.
       String.format("%4$2s %3$2s %2$2s %1$2s", "a", "b", "c", "d")
       // -> " d  c  b  a"   // Optional locale as the first argument can be used to get
       // locale-specific formatting of numbers.  The precision and width can be
       // given to round and align the value.
       String.format("e = %+10.4f", Math.E);
       // -> "e =    +2,7183"   // The '(' numeric flag may be used to format negative numbers with
       // parentheses rather than a minus sign.  Group separators are
       // automatically inserted.
       String.format("Amount gained or lost since last statement: $ %(,.2f",
                        balanceDelta);
       // -> "Amount gained or lost since last statement: $ (6,217.58)"
      

  6.   

    使用1.5以上的jdk最好标明一下
      

  7.   

    欢迎加入QQ群:32943114
    面向组件的软件开发, 专注net, java技术.
    探讨新一代软件特征webOS, 第三代搜索引擎技术,P2P,Grid,动态语言, AJAX, 虚拟操作系统
      

  8.   

    zhz586(最终幻想) ( ) 信誉:100    Blog  2006-12-25 11:11:20  得分: 0  
     
     
       
    简单的话,这样行不行
    字符串a+“20空格” 然后substring
      
     
    ///////////////////////////////////////////////////////////
    我觉得这样很好
      

  9.   

    substring左填充实现起来比较麻烦
      

  10.   


    System.out.println("右补空:["+String.format("%1$-20s", str)+"]");没看懂那个20s的s是什么意思 能说明下吗?谢谢
      

  11.   

    If the argument arg is null, then the result is "null". If arg implements Formattable, then arg.formatTo is invoked. Otherwise, the result is obtained by invoking arg.toString(). arg.toString()出来的是什么? 还有arg.formatTo的作用?
      

  12.   

    System.out.println("右补空:["+String.format("%1$-20s", str)+"]");
    %1$-20s的含义是“%1$”第一个参数,“-20s”以右补空最少20个字符的方式转换
    如果是20s就是左补空最少20个字符的方式转换
      

  13.   

    如果str的字符数多于20个,按实际字符输出的,只有str长度小于20才会填充
      

  14.   

    发现formatstring在处理中文的时候有致命缺点 输出时中文的2字节当作1字节处理了 sigh 还是要自己慢慢写 不能偷懒
      

  15.   

    谢谢大家 用了fool_leave的方法 把stringbuffer 换成了 stringbuilder 非常感谢welshem的热心帮助 ^_^