2011-12-19 13 views
11

文字列を考慮してください。Javaで可変数の引数を使用する文字列フォーマット

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

私たちは、私が"Entered number = 1 and string = abcd "のような文字列を取得するように私は、筋力にこれらの引数を置き換えることが可能な任意の方法があります私はオブジェクト

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

のリストを持っているとしましょうか?

これを一般化することで、すべての質問と引数をファイル(jsonなど)にダンプし、実行時にそれらを実行することを計画していました。 これを行うより良い方法があるかどうか教えてください。適切な

+0

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

答えて

23

てみてくださいとして

+0

+1シンプルで上品な答えです。ありがとう – Nithin

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

使用変数:

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

これは与える:

Entered number = 1 and string = 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にこの質問を参照してください!

関連する問題