2011-12-19 41 views
11

Xem xét một chuỗi.Định dạng chuỗi với số lượng đối số thay đổi trong java

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

Hãy để chúng tôi nói rằng tôi có một danh sách các đối tượng

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

Có cách nào mà tôi có thể thay thế những args vào Str, do đó tôi nhận được một chuỗi như "Entered number = 1 and string = abcd "?

Bằng cách khái quát hóa điều này, tôi đã lên kế hoạch kết xuất tất cả các câu hỏi và đối số trong một tệp (như json) và thực thi chúng tại thời gian chạy. Vui lòng cho tôi biết nếu có cách nào tốt hơn để thực hiện việc này.

+0

str.replaceAll ("% d", (Chuỗi) args.get (1)); – Zohaib

Trả lời

23

Hãy thử:

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

Điều này cho phép:

Entered number = 1 and string = abcd 
+0

+1 cho câu trả lời đơn giản và thanh lịch. Cảm ơn – Nithin

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

Sử dụng các biến cho phù hợp

6

Bạn có thể sử dụng như sau:

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

sẽ cho kết quả:

Entered number = 1 and string = abcd 

Từ 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. 

Xem câu hỏi này trên StackOverflow!

Các vấn đề liên quan