Java Equivalent to .NET's String.Format

29,745

Solution 1

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"

Solution 2

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

Solution 3

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

Solution 4

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

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:

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().

Solution 5

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

Share:
29,745
BuddyJoe
Author by

BuddyJoe

I like to code C# and work with the web. Still learning.

Updated on July 08, 2022

Comments

  • BuddyJoe
    BuddyJoe almost 2 years

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

  • skeryl
    skeryl over 12 years
    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.
  • nikib3ro
    nikib3ro about 11 years
    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.
  • AxA
    AxA about 9 years
    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?).
  • Zintom
    Zintom over 3 years
    It's prettier to concatenate the strings in Java, why did they make the syntax so complicated for such a commonly used function!