I find myself very frequently wanting to write reusable strings with parameter placeholders in them, almost exactly like what you'd find in an SQL PreparedStatement.
Here's an example
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. }
Does something like this exist already in Java ? Or, is there a better way to address something like this ?
What I'm really asking: is this ideal ?
Since Java 5, you can use String.format to parametrize Strings. Example: 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);
Cursor addressing and other strings requiring arguments are described by a argumentized string capability with escapes in a form (%x) comparable to printf(). For example, to address the cursor, the cup capability is given, using two arguments: the row and column to address to.
The Java String. format() method returns the formatted string by a given locale, format, and argument. If the locale is not specified in the String. format() method, it uses the default locale by calling the Locale.
String.format()
Since Java 5, you can use String.format
to parametrize Strings. Example:
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);
See http://docs.oracle.com/javase/tutorial/java/data/strings.html
Alternatively, you could just create a wrapper for the String
to do something more fancy.
MessageFormat
Per the comment by Max and answer by Affe, you can localize your parameterized String with the MessageFormat
class.
You could use String.format
. Something like:
String message = String.format("You requested %2$s but were assigned %1$s", "foo", "bar");
will generate
"You requested bar but were assigned foo"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With