MessageFormat 提供了以與語言無關方式生成連接消息的方式。使用此方法構造向終端用戶顯示的消息。
MessageFormat 獲取一組對象,格式化這些對象,然后將格式化后的字符串插入到模式中的適當位置
String類的format()方法用於創建格式化的字符串以及連接多個字符串對象。
package com.java.test; import java.text.MessageFormat; public class TestFormat { public static void main(String args[]){ String str="今天是{0}年{1}月{2}號,天氣{3}"; String str1="今天是%s年%d月%d號,天氣%s"; Object[] a={"2018","11","23","晴"}; System.out.println(MessageFormat.format(str,"2018","11","23","晴")); System.out.println(MessageFormat.format(str,a)); System.out.println(String.format("今天是%s年%d月%d號,天氣%s","2018",11,23,"晴")); System.out.println(String.format(str1,"2018",11,23,"晴")); } }
結果: