JAVA格式化字符串的两种方法

249 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第14天,点击查看活动详情

一、MessageFormat.format

根据顺序和占位符来对应插入的,占位符是{0},{1},{2},等这种形式作为占位符,占位符后面是顺序对应的值。它有两种使用方式:

1、使用静态方法format()

String result = MessageFormat.format("{0} -> {1}", "Hello", "world")  // Hello -> world


public static void main(String[] args){
    String a= "aaa";
    String b= "bb";
    String c= "c";
    System.out.println(MessageFormat.format("第一个是:{0},第二个是:{1} ,第三个是:{2}", a, b,null));

    System.out.println(MessageFormat.format("第一个是:''{0}'',第二个是:'{1}',第3个是:{2}", a, b,""));
}
输出:
第一个是:aaa,第二个是:bb ,第三个是:null
第一个是:'aaa',第二个是:{1},第3个是:

结论:

  • 1、如果结果想加上一个单引号,需要在相应占位符上加上两个单引号,才能准确转换。

  • 2、如果传入的参数为null,会自动替换为null。

  • 3、如果占位符被单引号包裹,占位符失效。

  • 4、如果想替换为空白或者其他的字符,可以使用StringUtils.defaultIfBlank(d,"结果") 替换。

2、创建公用对象使用

//创建固定格式模板
MessageFormat messageFormat = new MessageFormat("{0} -> {1}");
// 使用的时候需要传入Object类型的数组
String result =  messageFormat.format(new Object[]{"Hello", "world"});

3、使用pattern格式

在format中可以用那些pattern格式

image.png

FormatType定义传入内容的类型

image.png

二、String.format

String.format()字符串常规类型格式化的两种重载方式

  • format(String format, Object… args) 新字符串使用本地语言环境,制定字符串格式和参数生成格式化的新字符串。
  • format(Locale locale, String format, Object… args) 使用指定的语言环境,制定字符串格式和参数生成格式化的字符串。

image.png

image.png

使用举例:

public static void main(String[] args){
    Date date = new Date();
    System.out.println(String.format("%+d", 15));
    System.out.println(String.format("%04d", 9));
    //$使用
    System.out.println(String.format("格式参数$的使用:%1$d,%2$s", 99, "abc"));
    //+使用
    System.out.println(String.format("显示正负数的符号:%+d与%d%n", 99, -99));
    //补O使用
    System.out.println(String.format("最牛的编号是:%03d%n", 7));
    //空格使用
    System.out.println(String.format("Tab键的效果是:% 8d%n", 7));
    //.使用
    System.out.println(String.format("整数分组的效果是:%,d%n", 9989997));
    //空格和小数点后面个数
    System.out.println(String.format("一本书的价格是:% 50.5f元%n", 49.8));
    System.out.println(String.format(String.format(Locale.US, "英文月份简称:%tb", date)));
    System.out.println(String.format("本地月份简称:%tb%n", date));
    //B的使用,月份全称
    System.out.println(String.format(Locale.US, "英文月份全称:%tB", date));
    //f的使用
    System.out.println(String.format("年-月-日格式:%tF%n", date));
    //d的使用
    System.out.println(String.format("月/日/年格式:%tD%n", date));

}
输出结果:
+15
0009
格式参数$的使用:99,abc
显示正负数的符号:+99与-99
最牛的编号是:007
Tab键的效果是:       7
整数分组的效果是:9,989,997
一本书的价格是:                                          49.80000元
英文月份简称:Aug
本地月份简称:八月
英文月份全称:August
年-月-日格式:2022-08-13
月/日/年格式:08/13/22