.NET中的String.Format(可能只适用于VB.NET)将{0},{1}等转换为确定的字符串,例如:
Dim St As String = "Test: {0}, {1}"
Console.WriteLine(String.Format(St, "Text1", "Text2"))
我尝试在谷歌和StackOverflows中搜索,但它们都返回数字字符串格式。
.NET中的String.Format(可能只适用于VB.NET)将{0},{1}等转换为确定的字符串,例如:
Dim St As String = "Test: {0}, {1}"
Console.WriteLine(String.Format(St, "Text1", "Text2"))
我尝试在谷歌和StackOverflows中搜索,但它们都返回数字字符串格式。
其他建议当然也很好,但更多地是采用了类似于 printf
及其衍生的风格,这些是较近期添加到Java中的。您发布的代码看起来受到了 MessageFormat
的启发。
String format = "Test: {0}, {1}"
System.out.println(MessageFormat.format(format, "Text1", "Text2"))
我不是很确定'Return:'
语句的作用。
使用MessageFormat.format
,你也可以在替换标记中提供格式化参数。
message = MessageFormat.format("This is a formatted percentage " +
"{0,number,percent} and a string {1}", varNumber, varText);
System.out.println(message);
message = MessageFormat.format("This is a formatted {0, number,#.##} " +
"and {1, number,#.##} numbers", 25.7575, 75.2525);
System.out.println(message);
另外,也可以使用String.format
,但这不能保证位置的准确性,例如:String.format("如果你将%d乘以%s,你会得到什么?", varNumber, varText);
。
String.format("Test: %s, %s",string1,string2)
System.out.printf()
System.out.format()
使用其他方法:
StringBuilder sb = new StringBuilder();
Formatter f = new Formatter(sb, Locale.US);
f.format("my %s", "string");