java - 在 String.format() 中选择参数

C# 中,您可以使用 para 2: {2} 指定用于格式化字符串的参数。这允许在任意位置多次使用参数。

有没有办法用标准 java 做到这一点?

最佳答案

是的。您可以定义参数的索引,参见 API 的 参数索引 部分.

例如:

//                 ┌ argument 3 (1-indexed)
//                 | ┌ type of String
//                 | |  ┌ argument 2
//                 | |  | ┌ type of decimal integer
//                 | |  | |  ┌ argument 1
//                 | |  | |  | ┌ type of decimal number (float)
//                 | |  | |  | |
System.out.printf("%3$s %2$d %1$f", 1.5f, 42, "foo");

输出

foo 42 1.500000

注意

以下成语都有相同的格式定义:

  • String#format
  • PrintStream#printf
  • Formatter#format

https://stackoverflow.com/questions/30099071/

相关文章:

c++ - 使用 boost::date_time 库以毫秒为单位格式化时间

java - 通过 HotKey 在 Eclipse 中防止代码格式化

c# - 使 Console.WriteLine() 换行而不是字母

python - 使用 Python 在 OpenOffice/Microsoft Word 中格式

regex - 正则表达式中的 C# 字符串格式占位符

c# - 将电话号码解析为其部分

php - 定义跨平台money_format函数(Linux和Windows)

c# - JSON 序列化输出具有 C# 转义格式

c# - 在 C# 中格式化大数

css - Google Webfonts 在 Firefox、Chrome 和 Opera 中的呈