[英]String formatting with variable number of arguments in java
考慮一個字符串。
String Str = "Entered number = %d and string = %s"
讓我們說我有一個對象列表
List<Objects> args = new ArrayList<Objects>();
args.add(1);
args.add("abcd");
有沒有什么方法可以將這些args替換成Str,這樣我就得到一個像"Entered number = 1 and string = abcd "
?
通過概括,我計划將所有問題和參數轉儲到文件(如json)中,並在運行時執行它們。 如果有更好的方法,請告訴我。
嘗試:
String formatted = String.format(str, args.toArray());
這給出了:
Entered number = 1 and string = abcd
您可以使用以下內容:
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格式參數 :
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上看到這個問題!
final String myString = String.format(Str, 1, "abcd");
適當使用變量
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.