42

我发现自己经常想要编写带有参数占位符的可重用字符串,几乎与您在 SQL PreparedStatement 中找到的完全一样。

这是一个例子

private static final String warning = "You requested ? but were assigned ? instead.";

public void addWarning(Element E, String requested, String actual){

     warning.addParam(0, requested);
     warning.addParam(1, actual);
     e.setText(warning);
     //warning.reset() or something, I haven't sorted that out yet.
}

Java中是否已经存在类似的东西?或者,有没有更好的方法来解决这样的问题?

我真正要问的是:这是理想的吗?

4

8 回答 8

78

String.format()

从 Java 5 开始,您可以使用String.format参数化字符串。例子:

String fs;
fs = String.format("The value of the float " +
                   "variable is %f, while " +
                   "the value of the " + 
                   "integer variable is %d, " +
                   " and the string is %s",
                   floatVar, intVar, stringVar);

请参阅http://docs.oracle.com/javase/tutorial/java/data/strings.html

或者,您可以创建一个包装器String来做一些更花哨的事情。

MessageFormat

根据Max的评论和Affe 的回答,您可以使用该类本地化您的参数化字符串MessageFormat

于 2012-04-04T21:03:35.033 回答
15

你可以使用String.format. 就像是:

String message = String.format("You requested %2$s but were assigned %1$s", "foo", "bar");

会产生

"You requested bar but were assigned foo"
于 2012-04-04T21:04:10.157 回答
7

它是内置的,是的。您要查找的类是java.text.MessageFormat

于 2012-04-04T21:05:43.967 回答
2

Java 字符串格式化程序

于 2012-04-04T21:03:42.160 回答
1

String 类提供以下格式方法,http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html。例如(根据原始帖子):

private final static String string = "You requested %s but were assigned %s instead.";

public void addWarning(Element e, String requested, String actual) {
String warning = String.format(string, requested, actual);
e.setText(warning);
于 2012-04-04T21:43:58.383 回答
0

我可能会做类似的事情:

private final String warning = String.format("You requested %s but were assigned %s instead.", requested, actual);

如果您想在调用之前放置参数化字符串以格式化字符串,您可以执行如下所示的操作,尽管这不太清楚。

这些解决方案都不是天生可本地化的。如果您希望支持非英语语言环境,您可能需要考虑类似 .properties 文件。

private static final String warning = "You requested %s but were assigned %s instead.";

public void addWarning(Element E, String requested, String actual){
     e.setText(String.format(warning, requested, actual);
     //warning.reset() or something, I haven't sorted that out yet.
}
于 2012-04-04T21:08:35.417 回答
0

格式化程序可以为您执行此操作(还有一些附加功能,例如添加前导零间隔等等)

private static final String warning = "您请求了 %1$s,但被分配了 %2$s。";

public void addWarning(Element E, String requested, String actual){
     Formatter f = new Formatter();//you'll need to recreate it each time
     try{
         f.format(warning,requested,actual);
         e.setText(f.out().toString());
    }finally{f.close();}

}
于 2012-04-04T21:17:00.007 回答
-1

好吧,如果您的 String 是final您确定以后无法修改它。我不知道您是否可以为这种事情找到更好的用例,就像您可以简单地做的那样:

public void addWarning(Element E, String requested, String actual){

     String warning = "You requested" + requested + " but were assigned " + actual + " instead."     
     e.setText(warning);
}
于 2012-04-04T21:05:38.053 回答