简体   繁体   English

Java相当于.NET的String.Format

[英]Java Equivalent to .NET's String.Format

Java中有.NET的String.Format吗?

The 10 cent answer to this is: 对此的10美分答案是:

C#'s C#的


String.Format("{0} -- {1} -- {2}", ob1, ob2, ob3)

is equivalent to Java's 相当于Java的


String.format("%1$s -- %2$s -- %3$s", ob1, ob2, ob3)

Note the 1-based index, and the "s" means to convert to string using .toString(). 注意基于1的索引,“s”表示使用.toString()转换为字符串。 There are many other conversions available and formatting options: 还有许多其他转换和格式选项:

http://download.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax http://download.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax

Have a look at the String.format and PrintStream.format methods. 看看String.formatPrintStream.format方法。

Both are based on the java.util.Formatter class . 两者都基于java.util.Formatter类

String.format example: 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 example: System.out.format示例:

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

MessageFormat.format()使用.net表示法。

You can also simply use %s for string since the index is an optionnal argument. 您也可以简单地将%s用于字符串,因为索引是一个optionnal参数。

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

It's less noisy. 它不那么吵了。

Note about %s from the java documentation: 请注意java文档中的%s

If the argument arg is null, then the result is "null". 如果参数arg为null,则结果为“null”。 If arg implements Formattable, then arg.formatTo is invoked. 如果arg实现了Formattable,则调用arg.formatTo。 Otherwise, the result is obtained by invoking arg.toString(). 否则,通过调用arg.toString()获得结果。

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

This isn't really an answer to the OP's question, but may be helpful to others who are looking for a simple way of performing substitution of strings into a string containing C#-style "format items". 这不是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();
   }

(And in case you're curious, I'm using this code as part of a simple wrapper for the Android Log methods, to make it easier to log multiple things in a single log message.) (如果你很好奇,我正在使用这段代码作为Android Log方法的简单包装器的一部分,以便更容易在单个日志消息中记录多个内容。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM