我可以在 java 中格式化 2 次字符串吗?

Can I format a string in 2 times in java?

假设我有一个这样的字符串:

String toFormatS = "%s, %s ; %s, %s";

有没有办法像这样用 2 个连续的 Format 来合成这个字符串?

if (condition1) {
     toFormatS = String.Format(toFormatS, "foo", "foo2");
// that would make toFormatS equals to "foo, foo2 ; %s, %s"
}
if (condition2) {
     toFormatS = String.Format(toFormatS, "foo3", "foo4");
// that would make toFormatS equals to "foo, foo2 ; foo3, foo4"
}

我想这样做是因为我有一个函数 returns 一个没有 %s if !condition1 的字符串,2 %s if condition1 和 4 如果 condition1 && condition2

这是使用 Turo 回答的结果:

public String getFormatS(int i) {
   String r = "result : "+i;
   if (i > 15) {
     r += "1 : %s, %s";
   }
   if (i > 20) {
     r += "2 : %s, %s";
   } 
}

...
String s = getFormatS(x);
if (x > 15) {
     String.Format(s, "foo1", "foo2", "%s", "%s");
}
if (x > 20) {
     String.Format(s, "foo3", "foo4");
}

既然你告诉我我可以添加额外的参数我可以做到

String.Format(getFormatS(x), "foo1", "foo2", "foo3", "foo4")

但是 foos 是由昂贵的函数生成的,如果不需要,我宁愿不调用它们。

不,但你可以

if (condition1) {
     toFormatS = String.format(toFormatS, "foo", "foo2", "%s", "%s");
// that would make toFormatS equals to "foo, foo2 ; %s, %s"
}
if (condition2) {
     toFormatS = String.Format(toFormatS, "foo3", "foo4");
// that would make toFormatS equals to "foo, foo2 ; foo3, foo4"
}

并且忽略格式中的许多参数。

原格式的最后两个%符号转义就可以了。

String toFormatS = "%s, %s ; %%s, %%s";
if (condition1) {
    toFormatS = String.format(toFormatS, "foo", "foo2");
    // that would make toFormatS equals to "foo, foo2 ; %s, %s"
}
        
if (condition2) {
    toFormatS = String.format(toFormatS, "foo3", "foo4");
    // that would make toFormatS equals to "foo, foo2 ; foo3, foo4"
}