2011-12-19 14 views
11

Considere una cadena.Formato de cadena con número variable de argumentos en java

String Str = "Entered number = %d and string = %s" 

Digamos que tengo una lista de objetos

List<Objects> args = new ArrayList<Objects>(); 
args.add(1); 
args.add("abcd"); 

¿Hay alguna forma en la que puedo sustituir estos argumentos en Str, por lo que me sale una cadena como "Entered number = 1 and string = abcd "?

Al generalizar esto, estaba planeando volcar todas las preguntas y argumentos en un archivo (como json) y ejecutarlos en tiempo de ejecución. Háganme saber si hay mejores formas de hacerlo.

+0

str.replaceAll ("% d", (String) args.get (1)); – Zohaib

Respuesta

23

Proveedores:

String formatted = String.format(str, args.toArray()); 

esto da:

Entered number = 1 and string = abcd 
+0

+1 para una respuesta simple y elegante. Gracias – Nithin

1
final String myString = String.format(Str, 1, "abcd"); 

Usar variables según el caso

6

Usted puede usar la siguiente:

String str = "Entered number = %d and string = %s"; 

List<Object> args = new ArrayList<Object>(); 
args.add(1); 
args.add("abcd"); 

System.out.println(String.format(str, args.toArray())); 

dará la salida:

Entered number = 1 and string = abcd 

De JLS 8.4.1 Format parameters:

The last formal parameter in a list is special; 
it may be a variable arity parameter, indicated by an 
elipsis following the type. 

If the last formal parameter is a variable arity parameter of type T, 
it is considered to define a formal parameter of type T[]. 
The method is then a variable arity method. Otherwise, it is a fixed arity 
method. Invocations of a variable arity method may contain more actual 
argument expressions than formal parameters. All the actual argument 
expressions that do not correspond to the formal parameters preceding 
the variable arity parameter will be evaluated and the results stored 
into an array that will be passed to the method invocation. 

Ver esta pregunta en StackOverflow!

Cuestiones relacionadas