9

Any similar method to sprintf in Java?

Deepak
  • 2,094
  • 8
  • 35
  • 48
user496949
  • 83,087
  • 147
  • 309
  • 426
  • possible duplicate of [Sprintf equivalent in Java](http://stackoverflow.com/questions/47045/sprintf-equivalent-in-java) – reinierpost Nov 25 '14 at 10:41

6 Answers6

14

In a way the String.format is like having a Java sprintf method available here

String status = String.format("The rename status is (%d)", RENAME_SUCCEEDED);

You can see the example here as well

GustyWind
  • 3,026
  • 3
  • 41
  • 50
10

You're looking for

String.format.

Vladimir Ivanov
  • 42,730
  • 18
  • 77
  • 103
8

Complicated way (using Formatter)

StringBuilder sb = new StringBuilder();
// Send all output to the Appendable object sb
Formatter formatter = new Formatter(sb, Locale.US);

// Explicit argument indices may be used to re-order output.
formatter.format("%4$2s %3$2s %2$2s %1$2s", "a", "b", "c", "d")

Or simpler way:

String.format
Dewfy
  • 23,277
  • 13
  • 73
  • 121
  • @user496949 - per SDK you can use same argument two or more times in any order, `%[argument_index$][flags][width][.precision]conversion` - so index$ - is optional marker that allows you specify format string in other orders than source arguments. – Dewfy Mar 09 '11 at 10:47
2

Yes: Formatted Printing for Java (sprintf)

Bart Kiers
  • 166,582
  • 36
  • 299
  • 288
1

Have a look at the Formatter classs and Javadoc:

http://download.oracle.com/javase/6/docs/api/java/util/Formatter.html

Puce
  • 37,247
  • 13
  • 80
  • 152
0

Apparently the irrational prejudice against unsigned numeric data extends to this as well. The %u format element is conspicuously absent from the supported set.

Jerry Miller
  • 921
  • 1
  • 8
  • 11