2011-12-19 29 views
11

考慮一個字符串。在java中使用可變數量的參數進行字符串格式化

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

讓我們說我有對象的列表

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

有什麼辦法中,我可以替代這些ARGS進入海峽,讓我得到這樣"Entered number = 1 and string = abcd "一個字符串?

通過一般化我打算將所有問題和參數轉儲到文件(如json)中並在運行時執行它們。 請讓我知道是否有更好的方法來做到這一點。

+0

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

回答

23

嘗試:

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

這給:

Entered number = 1 and string = abcd 
+0

+ +1爲簡單和優雅的答案。謝謝 – Nithin

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

使用變量適當

6

您可以使用以下方法:

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())); 

會給輸出:

Entered number = 1 and string = abcd 

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. 

查看StackOverflow這個問題!

相關問題