Java Equivalent to .NET's String.Format
Asked Answered
J

6

63

Is there an equivalent to .NET's String.Format in Java?

Jennine answered 20/9, 2010 at 19:3 Comment(0)
C
31

Have a look at the String.format and PrintStream.format methods.

Both are based on the java.util.Formatter class.

String.format example:

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:

// Writes a formatted string to System.out.
System.out.format("Local time: %tT", Calendar.getInstance());
// -> "Local time: 13:34:18"
Commemorate answered 20/9, 2010 at 19:12 Comment(0)
A
125

The 10 cent answer to this is:

C#'s


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

is equivalent to Java's


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(). There are many other conversions available and formatting options:

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

Antiquate answered 25/3, 2011 at 20:32 Comment(3)
I knew there was a reason I like C# much, much better! Maybe it's because C# is the first language I learned, but the Java version looks contrived.Counterclockwise
The main reason C# looks cleaner is, it is newer language compared to Java. Syntactic sugar wasn't big those days (until Ruby came into prominence?).Lejeune
It's prettier to concatenate the strings in Java, why did they make the syntax so complicated for such a commonly used function!Dished
C
31

Have a look at the String.format and PrintStream.format methods.

Both are based on the java.util.Formatter class.

String.format example:

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:

// Writes a formatted string to System.out.
System.out.format("Local time: %tT", Calendar.getInstance());
// -> "Local time: 13:34:18"
Commemorate answered 20/9, 2010 at 19:12 Comment(0)
W
31

There is MessageFormat.format() which uses the .net notation.

Whirlabout answered 11/6, 2012 at 9:57 Comment(1)
Just note that MessageFormat.format doesn't EXACTLY work the same, for example this: MessageFormat.format("<font color='{0}'>{1}</font>", "#112233", "Something") will return "<font color={0}>Something</font>". As you guessed, the problem is ' char - you rather need to supply: "<font color=\"{0}\">{1}</font>". Read for MessageFormat class guide for more.Pasqualepasqueflower
D
21

You can also simply use %s for string, since the index is an optional argument.

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

The above example looks cleaner in my opinion.

A note about %s from the java documentation:

If the argument arg is null, then the result is "null". If arg implements Formattable, then arg.formatTo is invoked. Otherwise, the result is obtained by invoking arg.toString().

Dirichlet answered 22/1, 2013 at 18:13 Comment(0)
T
7

There is a String.format in Java, although the syntax is a little different from in .NET.

Tetragrammaton answered 20/9, 2010 at 19:7 Comment(0)
C
3

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".

   /**
    * 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.)

Cellulitis answered 12/10, 2015 at 13:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.