Java字符串的格式化与输出

Java字符串的格式化与输出

在C语言中格式化输出能够通过printf()函数实现,在Java中无需借助第三方工具相同能够实现此功能。自Java SE5后,java也提供了C语言中printf()风格的格式化输出方法。

眼下,有三种方法实现格式化输出,參考例如以下:

一、格式化输出的三种方法

1.System.out.format()

Java SE5引入的format方法能够用于PrintStream或PrintWriter对象。当中也包含System.out对象。format()方法模仿自C的printf()。

假设你比較怀旧的话。也能够使用printf(),以下是一个简单的演示样例:

	/**System.out.format()和System.out.printf()方法使用演示样例
	 * System.out.format()和System.out.printf()两个方法是等价的
	 * */
	public void method_1() {
		int x = 5;
		double y = 5.332542;
		// 大家都会用的比較原始的方法:
		System.out.println("Row 1: [" + x + " " + y + "]");
		// 通过System.out.format()方式格式化输出
		System.out.format("Row 1: [%d %f]\n", x, y);
		// 或者通过System.out.printf()方式格式化输出
		System.out.printf("Row 1: [%d %f]\n", x, y);
	}/*输出:
		Row 1: [5 5.332542]
		Row 1: [5 5.332542]
		Row 1: [5 5.332542]
	 */// :~
能够看到,format()和printf()是等价的,它们仅仅须要一个简单的格式化字符串,加上一串參数就可以,每一个參数相应一个格式化修饰符。

2.使用Formatter类:

在Java中,全部新的格式化功能都由java.util.Formatter类处理。能够将Formatter看做一个翻译器。它将你的格式化字符串与数据翻译成须要的结果。当你创建一个Formatter对象的时候。须要向其构造器传递一些信息,告诉它终于的结果将向哪里输出:

	/**通过Formater类实现格式化输出*/
	public void method_2(){
		//设置输出目的地为屏幕(System.out返回的是一个打印流对象"PrintStream")
		Formatter  f= new Formatter(System.out);
		String name = "jack zhu";
		int age = 100;
		double stature = 178.536;//cm
		f.format("name:%s 、age:%d、stature: %.2f)\n", name, age, stature);//.2表示浮点数精度(2位)
	}/*输出:
	name:jack zhu 、age:100、stature: 178.54)
 */// :~

结果result将被输出到System.out(屏幕),Formatter的构造器经过重载能够接受多种输出目的地,只是最经常使用的还是PrintStream(System.out属于PrintStream)、OutputStream和File。


3.String.format()

String.format()是一个static方法,他接受与Formatter.format()方法一样的參数。但返回一个String对象。当你仅仅需使用format()方法一次的时候。String.format()用起来非常方便。比如:

	/**String.format()方法实现格式化输出:*/
	public void method_3(){
		int x = 5;
		double y = 5.332542;
		String result = String.format("Row 1: [%d %f]\n", x, y);
		System.out.println(result);
	}/*输出:
		Row 1: [5 5.332542]
	 */// :~


二、经常使用格式化修饰符參考:

像上面的几种格式化方法參数中控制格式的由%d 、%s等修饰符控制,修饰符能够看做是特殊的占位符,使用占位符来表示插入数据的位置和插入数据的类型。详细參考例如以下:

占位符 表示的数据类型
d
整数(十进制)
c
Unicode字符
b
Boolean值
s
String
f
浮点数(十进制)
e
浮点数(科学计数)
x
整数(十六进制)
h
散列码(十六进制)
%
占位说明符




http://www.ctosclub.com/forum.php?

mod=viewthread&tid=22





http://www.ctosclub.com






posted @ 2017-04-13 10:42  wzjhoutai  阅读(918)  评论(0编辑  收藏  举报