java - 重用 String.format 中的参数?

标签 java string string-formatting

String hello = "Hello";

String.format("%s %s %s %s %s %s", hello, hello, hello, hello, hello, hello);

hello hello hello hello hello hello 

hello 变量是否需要在调用 format 方法时重复多次,或者是否有一个速记版本可以让您指定一次参数以应用于所有 %s 个 token ?

最佳答案

来自 the docs :

  • The format specifiers for general, character, and numeric types have the following syntax:
        %[argument_index$][flags][width][.precision]conversion
 

可选的argument_index是一个十进制整数,表示参数在参数列表中的位置。第一个参数由 "1$" 引用,第二个参数由 "2$" 引用,以此类推

String.format("%1$s %1$s %1$s %1$s %1$s %1$s", hello);

关于java - 重用 String.format 中的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6891175/

相关文章:

java - 如果 ArrayList 的大小发生变化,如何从其中选择一个随机元素?

java - JPA 中可以有多个主键吗

python - 从字符串中删除字符并进行替换不起作用

c++ - 为什么编译器不能优化 std::string concat?

c - 强制用户以特定格式编写输入

java - 这两种字符串格式有什么区别?

java - 我的 linux (centos 6) 机器上的 java home 在哪里?

java - 如何使用Java读取电子邮件中的 Logo 和图像,其中电子邮件的内容是html/纯文本

string - 如何合并用于创建和删除的路径和文件名

python - % python 中的字符串运算符