【问题标题】:String formatting with variable number of arguments in javajava中具有可变数量参数的字符串格式
【发布时间】:2011-12-19 10:51:56
【问题描述】:

考虑一个字符串。

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)中并在运行时执行它们。 如果有更好的方法,请告诉我。

【问题讨论】:

  • str.replaceAll("%d", (String)args.get(1));

标签: java string formatting


【解决方案1】:

试试:

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

这给出了:

Entered number = 1 and string = abcd

【讨论】:

    【解决方案2】:

    您可以使用以下内容:

    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看到这个问题!

    【讨论】:

      【解决方案3】:
      final String myString = String.format(Str, 1, "abcd");
      

      酌情使用变量

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-12-29
        • 2020-11-22
        • 2011-09-02
        • 2020-11-23
        • 1970-01-01
        • 2021-04-07
        • 1970-01-01
        相关资源
        最近更新 更多