有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java onthefly字符串替换

我在代码中见过类似的东西

somestring = "Today is {0}, tomorrow is {1}";

我知道它会将另一个变量的值放入字符串中,但我该怎么做呢

更新:有几种方法可以达到这种效果,哪种方法最有效


共 (2) 个答案

  1. # 1 楼答案

    你可以使用java。文本MessageFormat类

  2. # 2 楼答案

    你看过MessageFormat文档了吗

    例如(一个例子)

     Object[] arguments = {
         new Integer(7),
         new Date(System.currentTimeMillis()),
         "a disturbance in the Force"
     };
    
     String result = MessageFormat.format(
         "At {1,time} on {1,date}, there was {2} on planet {0,number,integer}.",
         arguments);
    
     output: At 12:30 PM on Jul 3, 2053, there was a disturbance
               in the Force on planet 7.
    

    关于你的问题。效率,我只会在遇到性能问题时担心这一点,而这些问题与此相关。我认为上述方法是合理有效的——尤其是考虑到可能会有一些输出(标准输出或类似输出?)我认为这是一个更大的瓶颈