java.String.format &Formatter
o(∩_∩)o
String result = String.format("The format method is %s!", "great");
// result now equals "The format method is great!".
You don't need to use numbers to indicate positioning. By default, the position of the argument is simply the order in which it appears in the string.
You will always use a %
followed by some other characters to let the method know how it should display the string. %s
is probably the most common, and it just means that the argument should be treated as a string.
// 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
just uses a java.util.Formatter
, so for a full description of the options you can see the Formatter javadocs.
Instead of looking at the source code, you should read the javadoc String.format() and Formatter syntax
String aString = "world"; int aInt = 20; String.format("Hello, %s on line %d", aString, aInt );
To do what you tried ( use an argument index ) you use: n$
String.format("Line:%2$d. Value:%1$s. Result: Hello %1$s at line %2$d", aString, aInt );
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
2020-04-29 任务计划无法正常运行批处理文件的解决方法
2020-04-29 Oracle 中 NULL判断并替换