3 回答

TA贡献1752条经验 获得超4个赞
虽然之前的所有回复都是正确的,但它们都是Java语言。这是一个Scala示例:
val placeholder = "Hello %s, isn't %s cool?"
val formatted = placeholder.format("Ivan", "Scala")
我还有一篇关于制作format%可能有用的Python 操作符的博客文章。

TA贡献1815条经验 获得超13个赞
您无需使用数字来指示定位。默认情况下,参数的位置只是它在字符串中出现的顺序。
以下是使用此方法的正确方法示例:
String result = String.format("The format method is %s!", "great");
// result now equals "The format method is great!".
您将始终使用a %后跟其他一些字符让方法知道它应该如何显示字符串。 %s可能是最常见的,它只是意味着参数应该被视为一个字符串。
我不会列出所有选项,但我会举几个例子来给你一个想法:
// we can specify the # of decimals we want to show for a floating point:
String result = String.format("10 / 3 = %.2f", 10.0 / 3.0);
// result now equals "10 / 3 = 3.33"
// we can add commas to long numbers:
result = String.format("Today we processed %,d transactions.", 1000000);
// result now equals "Today we processed 1,000,000 transactions."
String.format只使用a java.util.Formatter,所以有关选项的完整描述,您可以看到Formatter javadocs。
并且,正如BalusC所提到的,如果需要,您将在文档中看到可以更改默认参数排序。但是,您可能只需要/想要这样做的唯一时间就是您多次使用相同的参数。

TA贡献1765条经验 获得超5个赞
您应该阅读javadoc String.format()和Formatter语法,而不是查看源代码。
您可以在%之后指定值的格式。例如,对于十进制整数,它是d,对于String,它是s:
String aString = "world";
int aInt = 20;
String.format("Hello, %s on line %d", aString, aInt );
输出:
Hello, world on line 20
要执行您尝试的操作(使用参数索引),您使用:*n*$,
String.format("Line:%2$d. Value:%1$s. Result: Hello %1$s at line %2$d", aString, aInt );
输出:
Line:20. Value:world. Result: Hello world at line 20
添加回答
举报