Java 中的参数化字符串

新手上路,请多包涵

我发现自己经常想编写其中带有参数占位符的可重用字符串,几乎与您在 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 中是否已经存在类似的东西?或者,有没有更好的方法来解决这样的问题?

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

原文由 JHarnach 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 728
2 个回答

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 类本地化参数化字符串。

原文由 Garrett Hall 发布,翻译遵循 CC BY-SA 3.0 许可协议

您可以使用 String.format 。就像是:

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

会产生

"You requested bar but were assigned foo"

原文由 Keith Randall 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题