¿Existe un equivalente a .NET String.Format
en Java?Java Equivalente a String.Format de .NET
Respuesta
Eche un vistazo a los métodos String.format y PrintStream.format.
Ambos se basan en el java.util.Formatter class.
String.Format ejemplo:
Calendar c = new GregorianCalendar(1995, MAY, 23);
String s = String.format("Duke's Birthday: %1$tm %1$te,%1$tY", c);
// -> s == "Duke's Birthday: May 23, 1995"
ejemplo System.out.format:
// Writes a formatted string to System.out.
System.out.format("Local time: %tT", Calendar.getInstance());
// -> "Local time: 13:34:18"
Hay un String.format
en Java, aunque la sintaxis es un poco diferente de en .NET.
La respuesta 10 ciento a esto es:
C# 's
String.Format("{0} -- {1} -- {2}", ob1, ob2, ob3)
es equivalente a la de Java
String.format("%1$s -- %2$s -- %3$s", ob1, ob2, ob3)
Nota del índice basado en 1, y la "s" significa convertir en cadena utilizando .toString(). Hay muchas otras conversiones disponibles y opciones de formato:
http://download.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax
¡Sabía que había una razón por la que me gusta C# mucho, mucho mejor! Tal vez sea porque C# es el primer idioma que aprendí, pero la versión de Java parece artificial. – skeryl
La razón principal por la cual C# se ve más limpio es que es un lenguaje más nuevo en comparación con Java. El azúcar sintáctico no era grande esos días (¿hasta que Ruby adquirió importancia?). – rpattabi
Hay MessageFormat.format()
que utiliza la notación .net.
Este funciona exactamente como "me gusta".net – noni
Solo tenga en cuenta que MessageFormat.format no funciona EXACTAMENTE igual, por ejemplo esto: MessageFormat.format (" {1}", "# 112233", "Algo") devolverá " Something". Como ya habrás adivinado, el problema es 'char', es necesario suministrar: " {1}". Lea para la [guía de la clase MessageFormat] (http://developer.android.com/reference/java/text/MessageFormat.html) para obtener más información. – kape123
Esta debería ser la respuesta aceptada :) –
También puede simplemente usar %s
para la cadena ya que el índice es un argumento opcional.
String name = "Jon";
int age = 26;
String.format("%s is %s years old.", name, age);
Es menos ruidoso.
Nota sobre %s
de la documentación de Java:
Si el argumento arg es nulo, el resultado es "nula". Si arg implementa Formattable, entonces se invoca arg.formatTo. De lo contrario, el resultado se obtiene al invocar arg.toString().
Esto no es realmente una respuesta a la pregunta del OP, pero puede ser útil para otros que buscan una manera simple de realizar la sustitución de cadenas en una cadena que contiene "elementos de formato" estilo C#.
/**
* Method to "format" an array of objects as a single string, performing two possible kinds of
* formatting:
*
* 1. If the first object in the array is a String, and depending on the number of objects in the
* array, then a very simplified and simple-minded C#-style formatting is done. Format items
* "{0}", "{1}", etc., are replaced by the corresponding following object, converted to string
* (of course). These format items must be as shown, with no fancy formatting tags, and only
* simple string substitution is done.
*
* 2. For the objects in the array that do not get processed by point 1 (perhaps all of them,
* perhaps none) they are converted to String and concatenated together with " - " in between.
*
* @param objectsToFormat Number of objects in the array to process/format.
* @param arrayOfObjects Objects to be formatted, or at least the first objectsToFormat of them.
* @return Formatted string, as described above.
*/
public static String formatArrayOfObjects(int objectsToFormat, Object... arrayOfObjects) {
// Make a preliminary pass to avoid problems with nulls
for (int i = 0; i < objectsToFormat; i++) {
if (arrayOfObjects[i] == null) {
arrayOfObjects[i] = "null";
}
}
// If only one object, just return it as a string
if (objectsToFormat == 1) {
return arrayOfObjects[0].toString();
}
int nextObject = 0;
StringBuilder stringBuilder = new StringBuilder();
// If first object is a string it is necessary to (maybe) perform C#-style formatting
if (arrayOfObjects[0] instanceof String) {
String s = (String) arrayOfObjects[0];
while (nextObject < objectsToFormat) {
String formatItem = "{" + nextObject + "}";
nextObject++;
if (!s.contains(formatItem)) {
break;
}
s = s.replace(formatItem, arrayOfObjects[nextObject].toString());
}
stringBuilder.append(s);
}
// Remaining objects (maybe all of them, maybe none) are concatenated together with " - "
for (; nextObject < objectsToFormat; nextObject++) {
if (nextObject > 0) {
stringBuilder.append(" - ");
}
stringBuilder.append(arrayOfObjects[nextObject].toString());
}
return stringBuilder.toString();
}
(Y en caso de que estés curiosa, estoy usando este código como parte de un envoltorio sencillo para los métodos Android de registro, para que sea más fácil para registrar varias cosas en un solo mensaje de registro.)
- 1. Java equivalente a .NET System.InvalidOperationException
- 2. Java ¿Equivalente a DateTime.Parse de .NET?
- 3. Java equivalente a la NotSupportedException de .Net
- 4. C++ Equivalente de% ld en Java para String.format()
- 5. C# String.Format() ¿Equivalente en PHP?
- 6. Java equivalente a app.config?
- 7. Cómo ajustar Java String.format()?
- 8. java equivalente a printf ("% *. * F")
- 9. Constantes en .NET con String.Format
- 10. ¿Equivalente Java a la clase de versión de .NET?
- 11. Equivalente de TreeSet en Java a C# .net
- 12. ¿.NET tiene un equivalente a los archivos .properties de Java?
- 13. .Net equivalente al AssertionError de Java
- 14. equivalente de Java para MEF en .NET
- 15. ¿Qué es .NET equivalente de InterruptedException (Java)?
- 16. escapando caracteres de formato en java String.format
- 17. ¿Cuál es el equivalente a .NET SortedDictionary, en Java?
- 18. ¿Hay equivalente .NET TypeConverter en Java
- 19. .NET equivalente a Delphi's forceDirectory
- 20. ¿Existe un .Net equivalente a java.util.concurrent.Executor?
- 21. GWT equivalente para .NET?
- 22. ¿Hay .NET equivalente a ActionList de Delphi?
- 23. .NET equivalente de Java's List.subList()?
- 24. Java String.Format con el símbolo de moneda
- 25. De Java a .NET
- 26. .NET equivalente de StrCmpLogicalW
- 27. ¿Cuál es el equivalente .NET de NumberFormatException de Java?
- 28. .NET equivalente de size_t
- 29. ¿Cuál es el equivalente de Java de AggregateException de .net?
- 30. C# Equivalente a Java IdentityHashMap
La respuesta correcta dio 'Nicolas Guillaume'. – Alex78191