1、{index}:index必须是非负整数
String msg = "{0}{1}{2}{3}{4}{5}{6}{7}{8}";
Object[] array = new Object[]{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K"};
String value = MessageFormat.format(msg, array);
System.out.println(value); //ABCDEFGHI
2、两个单引号表示一个单引号,单个单引号会被省略(中文单引号不会被省略)
String value1 = MessageFormat.format("oh, {0} is ''a'' pig", "ZhangSan");
System.out.println(value1); //oh, ZhangSan is 'a' pig
String value2 = MessageFormat.format("oh, {0} is 'a' pig", "ZhangSan");
System.out.println(value2); //oh, ZhangSan is a pig
//中文单引号,不会被省略
String value3 = MessageFormat.format("oh, {0} is ‘a’ pig", "ZhangSan");
System.out.println(value3); //oh, ZhangSan is ‘a’ pig
String value = MessageFormat.format("oh, ''{0}'' is a pig", "ZhangSan");
System.out.println(value); //oh, 'ZhangSan' is a pig
//单引号会使其后面的占位符都失效
System.out.println(MessageFormat.format("'{0}'", 1)); //{0}
3、单引号会使其后面的占位符都失效,导致直接输出占位符
System.out.println(MessageFormat.format("{0}{1}", 1, 2)); //12
System.out.println(MessageFormat.format("'{0}{1}", 1, 2)); //{0}{1}
System.out.println(MessageFormat.format("'{0}{1}'", 1, 2)); //{0}{1}
System.out.println(MessageFormat.format("'{0}'-{1}", 1, 2)); //{0}-2
String value = MessageFormat.format("oh, {0,number,#.#} is good num", Double.valueOf("3.1415"));
System.out.println(value); //oh, 3.1 is good num
4、无论是有引号字符串还是无引号字符串,左花括号({)都是不支持的,使用左花括号会出现异常。因此,要使用到花括号时,需要使用单引号配合使用
String value1 = MessageFormat.format("oh, } is good num", Double.valueOf("3.1415"));
System.out.println(value1); //oh, } is good num
// String value2 = MessageFormat.format("oh, { is good num", Double.valueOf("3.1415"));
// System.out.println(value2); //java.lang.IllegalArgumentException: Unmatched braces in the pattern.
String value3 = MessageFormat.format("'{'{0}}", "X-rapido");
System.out.println(value3); //{X-rapido}
5、如果出现2个或2个以上左花括号({),就会出现分割字符串,但右花括号(})不会
String value1 = MessageFormat.format("oh, {{ is good num", "d");
System.out.println(value1); //oh,
String value2 = MessageFormat.format("oh, }} is good num", "d");
System.out.println(value2); //oh, }} is good num
6、如果需要显示双引号,要进行转义
String value = MessageFormat.format("oh, {0} is \"a\" pig", "ZhangSan");
System.out.println(value); //oh, ZhangSan is "a" pig
7、每调用一次MessageFormat.format()方法,都会新创建一个MessageFormat实例,相当于MessageFormat只使用了一次。如果要多次格式同一个模式的字符串,先创建一个MessageFormat实例,再执行格式化操作较好
//静态方法 MessageFormat.format() 的内部
public static String format(String pattern, Object... arguments) {
//每调用一次MessageFormat.format()方法,都会新创建一个MessageFormat实例
MessageFormat temp = new MessageFormat(pattern);
return temp.format(arguments);
}
//多次格式同一个模式的字符串,先创建一个MessageFormat实例,再执行格式化操作
String message = "oh, {0} is a pig";
Object[] array = new Object[]{"ZhangSan"};
//数组也可以这样定义
// String[] strArr = {"xxx", "xx", "xx"};
//先创建一个MessageFormat实例
MessageFormat messageFormat = new MessageFormat(message);
//再执行format()进行格式化操作
String value = messageFormat.format(array);
System.out.println(value);