Cadena de formato correcta para String.format o similar

I'm sure I've seen String.format used like this before:

String.format("Some {1}, {2}, {3}", var1, var2, var3);

Does this ring any bells for anyone? Maybe I'm thinking of C#, is there a way of achieving the same in java?

Sé que puedes hacer algo como:

String.format("Some %s, %d, %s", aString, aNumber, aString)

but the syntax I'm after is for the former...

preguntado el 26 de agosto de 12 a las 19:08

4 Respuestas

Lo que buscas es MessageFormat, which uses a given format and input parameters, e.g.

MessageFormat.format("Some {0}, {1}, {2}", var1, var2, var3);

Y como ya se mencionó, String.format can still do the job using the alternate syntax, but it is less powerful in functionality and not what you requested.

Respondido 26 ago 12, 19:08

Did some research: String.format is actually newer than MessageFormat. They do use different methods under the hood but don't differ much in overall functionality. String.format thus is said to be quicker. - Tobías N. Sasse

Nice. Exists in Android as well. A very simple way of formatting. Not needing to provide the type of the input is an advantage. - AlikElzin-kilaka

I do not like to specify both index of parameter or its type - mainly when throwing exception and preparing message for it. I like way SLF4j does it. So I wrapped org.slf4j.helpers.MessageFormatter like this:

public static String subst(String string, Object...objects) {
    return MessageFormatter.arrayFormat(string, objects).getMessage();
}

Entonces puedes usarlo así:

public void main(String[] args) {
    throw new RuntimeException(MyUtils.subst("Problem with A={} and B={}!", a, b));
}

Respondido 31 ago 16, 09:08

For most cases (one or 2 parameters), you can also use directly : MessageFormatter.format("Problem with A={} and B={}!", a, b); (still org.slf4j.helpers.MessageFormatter ) - tristan

Yes, that's the typical formato cadena de C#. In Java, you can use the latter, that is, String.format("%s %d %d", ...).

An alternativa es utilizar MessageFormat.format("Some {0}, {1}, {2}", var1, var2, var3), which uses the .NET curly braces notation, as mentioned by @Tobias, though it requires you to import java.text.MessageFormat. They are also more appropriate for when you are dealing with localized resources, where you typically have external .properties files with messages in the format Error {0} ocurred due to {1}.

Respondido 26 ago 12, 19:08

Si desea utilizar marcadores de posición vacíos (sin posiciones), puede escribir una pequeña utilidad alrededor Message.format(), Me gusta esto

    String format(String s, Object... var2) {
        int i = 0;
        while(s.contains("{}")) {
            s = s.replaceFirst(Pattern.quote("{}"), "{"+ i++ +"}");
        }
        return MessageFormat.format(s, var2);
    }

Y luego, puede usarlo como,

format("Some {} {} {}", var1, var2, var3);

contestado el 26 de mayo de 20 a las 14:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.