第13章 字符串

#本不想记录这一章的内容,但为了连贯性,列出不太熟悉的几个点#

13.5 格式化输出

printf和format的用法

 1 import static java.lang.System.out;
 2 public class Test {
 3   public static void main(String args[]){
 4     out.printf("%s, %f, %d\n", "abc", 5.4, 3);
 5     out.format("%s, %f, %d", "abc", 5.4, 3);
 6   }
 7 }/*Output:
 8 abc, 5.400000, 3
 9 abc, 5.400000, 3
10 */

Formatter类的用法

 1 import static java.lang.System.out;
 2 import java.util.*;
 3 public class Test {
 4   public static void main(String args[]){
 5     Formatter f = new Formatter(out);
 6     f.format("01234567890123456789012345678901\n");
 7     f.format("%-15s,%-5d,%10b\n", "abcdef", 123, false);
 8   }
 9 }/*Output:
10 01234567890123456789012345678901
11 abcdef         ,123  ,     false
12 */

String.format()的用法

 1 import static java.lang.System.out;
 2 public class Test {
 3     public static String format(byte[] data) {
 4         StringBuilder result = new StringBuilder();
 5         int n = 0;
 6         for(byte b: data){
 7             if( n % 16 == 0)
 8                 result.append(String.format("%05X: ", n));
 9             result.append(String.format("%2X ", b));
10             n++;
11             if(n % 16 == 0)
12                 result.append("\n");
13         }
14         result.append("\n");
15         return result.toString();
16     }
17     public static void main(String args[]){
18         out.print(Test.format(new byte[] {12,33,16,23,3,44,50,2,1,24,3,5,9,2,54,5,13,4,15,1,2,3,4,2,3,15,6,2,6,2,4,3,5,3,5,3,4,5}));
19     }
20 }/*Output:
21 00000:  C 21 10 17  3 2C 32  2  1 18  3  5  9  2 36  5 
22 00010:  D  4  F  1  2  3  4  2  3  F  6  2  6  2  4  3 
23 00020:  5  3  5  3  4  5 
24 */

#关于Rex,预留空地#

posted on 2013-05-03 14:10  peter9606  阅读(135)  评论(0编辑  收藏  举报

导航