【问题标题】:Java on-the-fly string replacementJava 即时字符串替换
【发布时间】:2012-01-01 08:57:50
【问题描述】:

我在代码中见过这样的东西

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

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

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

【问题讨论】:

    标签: java string replace


    【解决方案1】:

    您查看过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.
    

    关于你的问题。效率,如果您遇到性能问题并且它们与此相关,我只会担心这一点。我希望上述内容相当有效 - 特别是考虑到可能会涉及一些输出(到 std.out 或类似的?),我认为这是一个更大的瓶颈。

    【讨论】:

      【解决方案2】:

      我认为您的示例具体使用的是 java.text.MessageFormat。

      【讨论】:

        【解决方案3】:

        你可以使用 java.text.MessageFormat 类

        【讨论】:

          【解决方案4】:
          // Assuming variables today and tomorrow are strings.
          somestring = String.format("Today is %s, tomorrow is %s", today, tomorrow);
          

          【讨论】:

          • 如果我从 .properties 文件中获取第一个字符串,这会起作用吗?
          • 第一个字符串来自哪里并不重要,只要它是一个字符串。另外,如果你传递一个对象,我相信它只会为那个对象调用toString()
          猜你喜欢
          • 2021-01-27
          • 2015-05-02
          • 1970-01-01
          • 1970-01-01
          • 2015-09-10
          • 2015-12-23
          • 1970-01-01
          • 1970-01-01
          • 2015-05-01
          相关资源
          最近更新 更多