Java эквивалентно .NET String.Format - PullRequest
60 голосов
/ 20 сентября 2010

Есть ли эквивалент в .NET String.Format в Java?

Ответы [ 6 ]

115 голосов
/ 25 марта 2011

Ответ 10 центов на это:

C # *


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

эквивалентно


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

в Java.s "означает преобразовать в строку, используя .toString ().Есть много других доступных преобразований и вариантов форматирования:

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

31 голосов
/ 20 сентября 2010

Ознакомьтесь с методами String.format и PrintStream.format .

Оба основаны на классе java.util.Formatter .

Пример строки:

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"
29 голосов
/ 11 июня 2012

MessageFormat.format() использует нотацию .net.

18 голосов
/ 22 января 2013

Вы также можете просто использовать %s для строки, поскольку индекс является необязательным аргументом.

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

Это менее шумно.

Обратите внимание на %s из документации Java:

Если аргумент arg равен нулю, то результат равен нулю.Если arg реализует Formattable, то вызывается arg.formatTo.В противном случае результат получается вызовом arg.toString ().

7 голосов
/ 20 сентября 2010

В Java есть String.format, хотя синтаксис немного отличается от .NET.

3 голосов
/ 12 октября 2015

На самом деле это не ответ на вопрос ОП, но он может быть полезен для тех, кто ищет простой способ замены строк в строку, содержащую "элементы формата" стиля 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, чтобы упростить запись нескольких вещей в одном сообщении журнала.)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...