1. 程式人生 > 實用技巧 >字串用佔位符拼接 String ms = MessageFormat.format("{0,number,#.##}", 3.656);

字串用佔位符拼接 String ms = MessageFormat.format("{0,number,#.##}", 3.656);

public class Test {
public static void main(String[] args) {
String newContent = "\n\tprivate String {0};\n" +
"\tprivate boolean modify_{0} = false;\n" +
"\n" +
"\tpublic String {1}() '{'\n" +
"\t\treturn {0};\n" +
"\t'}'\n" +
"\n" +
"\tpublic void setBDCDYID(String {0}) '{'\n" +
"\t\tif (this.{0} != {0}) '{'\n" +
"\t\t\tthis.{0} = {0};\n" +
"\t\t\tmodify_{0} = true;\n" +
"\t\t'}'\n" +
"\t'}'";
String dd = MessageFormat.format(newContent,"bdcdyic","setBdcdyid");
System.out.println(dd);
    //特殊符號{ } 需要用左右單引號圍起來 '{' '}',否則和佔位符衝突
System.out.println(MessageFormat.format("{1} '{' '}' hello {0} {1}","world","lili"));
}

private String id;
public void setId(String id){
this.id = id;
}
}

第二個引數可選。

String ms = MessageFormat.format("{0,number,#.##}", 3.656);

若格式不匹配則報異常 如第二個引數限制為數值 但內容為 String

參考https://blog.csdn.net/Mr_Tony/article/details/50175447?utm_source=blogxgwz9