输出XXX{0}YYY{1}ZZZ格式的字符串方法


public static void main(String[] args) {

MessageFormat form = new MessageFormat("xxxxx{0}xx");

String[] testArgs=new String[]{"hello"};

System.out.println(form.format(testArgs));

}


[b]
使用MessageFormat控制输出[/b]
Printf是很多C语言程序员喜欢的工具,当他们转而使用Java时他们非常的失望。Java有一个替代的方法但是那个方法和C语言的printf() 函数的原理不一样。

幸运的是,早期的Java库的开发者熟悉到创建一个更合适Java的工具而不是一个printf函数。

MessageFormat运行开发者输出文本中的变量的格式。它是一个强大的类,就像下面的例子展示的那样:

String message =
"Once upon a time ({1,date}, around about {1,time,short}), there " +
"was a humble developer named Geppetto who slaved for " +
"{0,number,integer} days with {2,number,percent} complete user " +
"requirements. ";
Object[ ] variables = new Object[ ]
{ new Integer(4), new Date( ), new Double(0.21) }
String output = MessageFormat.format( message, variables );
System.out.println(output);

隐藏在信息中的是描述输出的格式的一种短小的代码,范例的输出如下:

Once upon a time (Nov 3, 2002, around about 1:35 AM), there was a humble developer
named Geppetto who slaved for 4 days with 21% complete user requirements.
假如相同的信息需要被重复输出但是变量的值不同,那么创建一个MessageFormat对象并给出信息。下面是上面的例子的修正版:

//String output = MessageFormat.format(message, variables );
//变为:
MessageFormat formatter = new MessageFormat(message);
String output = formatter.format(variables);


除了可以处理日期、时间、数字和百分数外,MessageFormat也可以处理货币,运行更多的数字格式的控制并且答应指定ChoiceFormat。

MessageFormat 是一个极好的类,它应该经常被使用但是现在还没有。它的最大的缺点是数据是被作为变量传递而不是一个Properties对象。一个简单的解决办法是写一 个封装类,它会预解析字符串为格式化的结果,将Properties的key转换为一个数组索引,顺序是Properties.keys( )返回的顺序。

转自:[url]http://hi.baidu.com/lvword/blog/item/c12313e7817ffc28b83820e1.html[/url]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值