Java字符串模版

转载文章:

http://www.jb51.net/article/67058.htm

http://www.cnblogs.com/fsjohnhuang/p/4094777.html


一、String.format方法

占位符: %[index$][标识]*[最小宽度][.精度]转换符

   % :占位符的其实字符,若要在占位符内部使用%,则需要写成 %% 。
  [index$] :位置索引从1开始计算,用于指定对索引相应的实参进行格式化并替换掉该占位符。
  [标识] :用于增强格式化能力,可同时使用多个 [标识] ,但某些标识是不能同时使用的。
  [最小宽度] :用于设置格式化后的字符串最小长度,若使用 [最小宽度] 而无设置 [标识] ,那么当字符串长度小于最小宽度时,则以左边补空格的方式凑够最小宽度。
  [.精度] :对于浮点数类型格式化使用,设置保留小数点后多少位。
  转换符 :用于指定格式化的样式,和限制对应入参的数据类型。

1、字符串格式化

占位符: %[index$][标识][最小宽度]转换符
可用标识:

             -:在最小宽度内左对齐,右边用空格补上。

转换符:

            s:字符串类型

            c:字符类型,实参必须为char或int、short等可转换为char类型的数据类型,否则抛出异常

            b:布尔类型,只要实参为非false的布尔类型,均格式化为字符串true,否则为字符串false

            n:平台独立的换行符

package com.learns.format;

public class StringTest {
	public static void main(String[] args) {
		
		String str = String.format("%1$s %2$s", "Hello","World!");
		System.out.println(str);
	}
}

2、对整数进行格式化

占位符: %[index$][标识]*[最小宽度]转换符

可用标识:

            -:在最小宽度内左对齐,不可以与0标识一起使用

            0:若内容长度不足最小宽度,则在左边用0来填充

            #:对8进制和16进制,8进制前添加一个0,16进制前添加0x

            +:结果总包含一个+或-号

            空格:正数前加空格,负数前加-号

            ,:只用于十进制,每3位数字间用,分隔

            (:若结果为负数,则用括号括住,且不显示符号

转换符:

             b:布尔类型,只要实参为非false的布尔类型,均格式化为字符串true,否则为字符串false

             d:整数类型(十进制)

             x:整数类型(十六进制)

             o:整数类型(八进制)

             n:平台独立的换行符

package com.learns.format;

public class StringTest {

	public static void main(String[] args) {
		// 0001 (1,000)
		String str = String.format("%1$04d %2$(,d",1,-1000);
		System.out.println(str);
	}
}

3、对浮点数进行格式化

占位符: %[index$][标识]*[最小宽度][.精度]转换符
可用标识:

            -:在最小宽度内左对齐,不可以与0标识一起使用

            0:若内容长度不足最小宽度,则在左边用0来填充

            #:对8进制和16进制,8进制前添加一个0,16进制前添加0x

            +:结果总包含一个+或-号

            空格:正数前加空格,负数前加-号

            ,:只用于十进制,每3位数字间用,分隔

            (:若结果为负数,则用括号括住,且不显示符号

转换符:

             b:布尔类型,只要实参为非false的布尔类型,均格式化为字符串true,否则为字符串false

             n:平台独立的换行符

             f:浮点数型(十进制)。显示9位有效数字,且会进行四舍五入。如99.99

             a:浮点数型(十六进制)

             e:指数类型。如9.38e+5

             g:浮点数型(比%f,%a长度短些,显示6位有效数字,且会进行四舍五入)

package com.learns.format;

public class StringTest {

	public static void main(String[] args) {
		// 123.457
		String str = String.format("%.3f",123.456789);
		System.out.println(str);
	}
}

4、对日期时间进行格式化

占位符: %[index$]t转换符

日期转换符:       

             c:星期六 十月 27 14:21:20 CST 2007
             F:2007-10-27
             D:10/27/07
             r:02:25:51 下午
             T:14:28:16
             R:14:28
             b:月份简称
             B: 月份全称
             a:星期简称
             A: 星期全称
             C:年前两位(不足两位补零)
             y:年后两位(不足两位补零)
             j:当年的第几天
            m:月份(不足两位补零)
            d:日期(不足两位补零)
            e:日期(不足两位不补零)

时间转换符:

            H: 24小时制的小时(不足两位补零)
            k:24小时制的小时(不足两位不补零)
            I:12小时制的小时(不足两位补零)
            i:12小时制的小时(不足两位不补零)
            M:分钟(不足两位补零)
            S:秒(不足两位补零)
            L:毫秒(不足三位补零)
            N:毫秒(不足9位补零)
            p:小写字母的上午或下午标记,如中文为“下午”,英文为pm
            z:相对于GMT的时区偏移量,如+0800
            Z:时区缩写,如CST
            s:自1970-1-1 00:00:00起经过的秒数
            Q:自1970-1-1 00:00:00起经过的豪秒

package com.learns.format;

import java.util.Date;

public class StringTest {

	public static void main(String[] args) {
		/*
		 * 结果
		 * 星期四 十二月 08 09:55:21 CST 2016
		 *  2016-12-08
		 *  12/08/16
		 */
		Date date = new Date();
		String str = String.format("%1$tc %n %2$tF %n %3$tD",date,date,date);
		System.out.println(str);
	}
}

5、其他转换符

<:用于格式化前一个转换符所描述的参数

package com.learns.format;

import java.util.Date;

public class StringTest {

	public static void main(String[] args) {
		/*
		 * 结果
		 * 星期四 十二月 08 09:55:21 CST 2016
		 *  2016-12-08
		 *  12/08/16
		 */
		Date date = new Date();
		String str = String.format("%tc %n %<tF %n %<tD",date);
		System.out.println(str);
	}
}

二、MessageFormat

占位符:

{ ArgumentIndex }
{ ArgumentIndex , FormatType }
{ ArgumentIndex , FormatType , FormatStyle }
ArgumentIndex:入参位置索引

FormatType:指定使用不同的Format子类对入参进行格式化处理。取值范围:

                     number:调用NumberFormat进行格式化

                     date:调用DateFormat进行格式化

                     time:调用DateFormat进行格式化

                     choice:调用ChoiceFormat进行格式化

FormatStyle:设置FormatType中使用的格式化样式。取值范围:short、medium、long、full、integer、currency、percent、SubformatPattern(子格式模式,形如#.##)

示例:

1、{0}和{1,number,short}和{2,number,#.#};都属于FormatElement,0,1,2是ArgumentIndex。
2、{1,number,short}里面的number属于FormatType,short则属于FormatStyle。
3、{1,number,#.#}里面的#.#就属于子格式模式。
指定FormatType和FormatStyle是为了生成日期格式的值、不同精度的数字、百分比类型等等。

package com.learns.format;

import java.text.MessageFormat;

public class FormatTest {
	public static void main(String[] args) {
		String value = MessageFormat.format("{0,number,#.#} is good num",Double.valueOf("3.14"));
		System.out.println(value);
	}
}

使用注意:

1、格式化字符串时,两个单引号才标识一个单引号,单个单引号会被忽略,中文单引号不会被忽略。

package com.learns.format;

import java.text.MessageFormat;

public class FormatTest {

	public static void main(String[] args) {
		// 单个单引号
		String str = MessageFormat.format("This is {0} 'we' play!","why");
		System.out.println(str);
		// 两个单引号
		String str2 = MessageFormat.format("This is {0} ''we'' play!","why");
		System.out.println(str2);
		// 中文单引号
		String str3 = MessageFormat.format("This is {0} ‘we’ play!","why");
		System.out.println(str3);
	}
}

结果:

This is why we play!
This is why 'we' play!
This is why ‘we’ play!

2、单引号会使其后面的占位符均失败,导致直接输出占位符。

package com.learns.format;

import java.text.MessageFormat;

public class FormatTest {

	public static void main(String[] args) {
		// 添加一个单引号在占位符前,占位符失败 
		String str = MessageFormat.format("This is '{0} {1} play!","why","we");
		System.out.println(str);
		// 占位符添加一对单引号,单个占位符失败
		String str2 = MessageFormat.format("This is '{0}' {1} play!","why","we");
		System.out.println(str2);
		// 占位符添加两个单引号,正常使用
		String str3 = MessageFormat.format("This is ''{0}'' {1} play!","why","we");
		System.out.println(str3);
	}
}
结果:

This is {0} {1} play!
This is {0} we play!
This is 'why' we play!

3、要单独使用左花括号,需要使用单引号。否则会出现异常

package com.learns.format;

import java.text.MessageFormat;

public class FormatTest {

	public static void main(String[] args) {
		// 使用花括号
		String str = MessageFormat.format("This is '{'{0}} {1} play!","why","we");
		System.out.println(str);
		// 出现两个或两个以上左花括号,会分割字符串。(与占位符连接会报错,如{{0})
		String str2 = MessageFormat.format("This is {{ {0} {1} play!","why","we");
		System.out.println(str2);
	}
}
结果:
This is {why} we play!
This is 

4、每调用一次MessageFormat.format方法,都会新创建MessageFormat的一个实例。因此若多次使用同一模式字符串,创建一个MessageFormat实例比较好。

源代码:

public static String format(String pattern, Object ... arguments) {
        MessageFormat temp = new MessageFormat(pattern);
        return temp.format(arguments);
    }


总结:

对于简单的格式化或字符串组装,使用MessageFormat.format。格式化处理更丰富要使用String.format方法


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值