java中参数数目可变的字符串格式
考虑一个字符串java中参数数目可变的字符串格式,java,string,formatting,Java,String,Formatting,考虑一个字符串 String Str = "Entered number = %d and string = %s" 假设我有一个对象列表 List<Objects> args = new ArrayList<Objects>(); args.add(1); args.add("abcd"); List args=new ArrayList(); 参数。添加(1); 参数添加(“abcd”); 是否有任何方法可以将这些arg替换为Str,从而得到一个类似于“Ente
String Str = "Entered number = %d and string = %s"
假设我有一个对象列表
List<Objects> args = new ArrayList<Objects>();
args.add(1);
args.add("abcd");
List args=new ArrayList();
参数。添加(1);
参数添加(“abcd”);
是否有任何方法可以将这些arg替换为Str,从而得到一个类似于“Entered number=1”和string=abcd“
”的字符串
通过概括这一点,我计划将所有问题和参数转储到一个文件(如json)中,并在运行时执行它们。
如果有更好的方法,请告诉我
final String myString = String.format(Str, 1, "abcd");
根据需要使用变量尝试:
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()));
发件人:
看到这个问题了吗 str.replaceAll(“%d”,(字符串)args.get(1));
Entered number = 1 and string = abcd
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.