Java中与.NET的String.Format相对应的方法是什么?

63

Java中是否有类似于.NET的String.Format的功能?

6个回答

125

23
我知道我更喜欢C#的原因了!也许是因为C#是我学习的第一种语言,但Java版本看起来很勉强。 - skeryl
1
C# 看起来更加简洁的主要原因是它相对于 Java 是一门较新的语言。在那个时代,语法糖并不是很流行(直到 Ruby 变得流行起来?)。 - rpattabi
在Java中连接字符串更加美观,为什么对于如此常用的函数却要使语法变得那么复杂! - Zintom

31
请查看String.formatPrintStream.format方法。
两者都基于java.util.Formatter类String.format示例:
Calendar c = new GregorianCalendar(1995, MAY, 23);
String s = String.format("Duke's Birthday: %1$tm %1$te,%1$tY", c);
// -> s == "Duke's Birthday: May 23, 1995"

System.out.format示例:

// Writes a formatted string to System.out.
System.out.format("Local time: %tT", Calendar.getInstance());
// -> "Local time: 13:34:18"

31

有一个MessageFormat.format()函数,它使用 .net 符号。


4
请注意,MessageFormat.format并不完全相同,例如这个例子:MessageFormat.format("<font color='{0}'>{1}</font>", "#112233", "Something")会返回"<font color={0}>Something</font>"。正如你所猜测的那样,问题出在 ' 字符上 - 你需要使用转义字符来提供正确的格式:<font color="{0}">{1}</font>"。请参阅MessageFormat类指南了解更多信息。 - nikib3ro

21

由于索引是可选参数,因此您还可以简单地使用字符串 %s

String name = "Jon";
int age = 26;
String.format("%s is %s years old.", name, age);

在我看来,上面的例子更加简洁。

有关java文档中%s的说明:

如果参数arg为null,则结果为“null”。如果arg实现了Formattable,则会调用arg.formatTo。否则,通过调用arg.toString()方法获取结果。


7

Java中有一个String.format方法,虽然语法与.NET略有不同。


3

这并不是对OP问题的真正回答,但可能对其他正在寻找一种简单方法将字符串替换为包含C#风格“格式项”的字符串的人有所帮助。

   /**
    * Method to "format" an array of objects as a single string, performing two possible kinds of
    * formatting:
    *
    * 1. If the first object in the array is a String, and depending on the number of objects in the
    *    array, then a very simplified and simple-minded C#-style formatting is done. Format items
    *    "{0}", "{1}", etc., are replaced by the corresponding following object, converted to string
    *    (of course). These format items must be as shown, with no fancy formatting tags, and only
    *    simple string substitution is done.
    *
    * 2. For the objects in the array that do not get processed by point 1 (perhaps all of them,
    *    perhaps none) they are converted to String and concatenated together with " - " in between.
    *
    * @param objectsToFormat  Number of objects in the array to process/format.
    * @param arrayOfObjects  Objects to be formatted, or at least the first objectsToFormat of them.
    * @return  Formatted string, as described above.
    */
   public static String formatArrayOfObjects(int objectsToFormat, Object... arrayOfObjects) {

      // Make a preliminary pass to avoid problems with nulls
      for (int i = 0; i < objectsToFormat; i++) {
         if (arrayOfObjects[i] == null) {
            arrayOfObjects[i] = "null";
         }
      }

      // If only one object, just return it as a string
      if (objectsToFormat == 1) {
         return arrayOfObjects[0].toString();
      }

      int nextObject = 0;
      StringBuilder stringBuilder = new StringBuilder();

      // If first object is a string it is necessary to (maybe) perform C#-style formatting
      if (arrayOfObjects[0] instanceof String) {
         String s = (String) arrayOfObjects[0];

         while (nextObject < objectsToFormat) {

            String formatItem = "{" + nextObject + "}";
            nextObject++;
            if (!s.contains(formatItem)) {
               break;
            }

            s = s.replace(formatItem, arrayOfObjects[nextObject].toString());
         }

         stringBuilder.append(s);
      }

      // Remaining objects (maybe all of them, maybe none) are concatenated together with " - "
      for (; nextObject < objectsToFormat; nextObject++) {
         if (nextObject > 0) {
            stringBuilder.append(" - ");
         }
         stringBuilder.append(arrayOfObjects[nextObject].toString());
      }

      return stringBuilder.toString();
   }

(如果你好奇的话,我正在使用这段代码作为Android Log方法的简单包装器的一部分,以便更轻松地在单个日志消息中记录多个内容。)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接