Any similar method to sprintf in Java?
Asked
Active
Viewed 1.2k times
9
-
possible duplicate of [Sprintf equivalent in Java](http://stackoverflow.com/questions/47045/sprintf-equivalent-in-java) – reinierpost Nov 25 '14 at 10:41
6 Answers
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
- 22,648
- 12
- 68
- 116
-
@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
Bart Kiers
- 161,100
- 35
- 287
- 281
-
Sadly this link redirects to generic page http://www.oracle.com/technetwork/java/index.html – Russell Silva Apr 08 '13 at 22:23
-
1@RussellSilva, changed the link to point to an archived version of the article. – Bart Kiers Apr 09 '13 at 09:52
1
Have a look at the Formatter classs and Javadoc:
http://download.oracle.com/javase/6/docs/api/java/util/Formatter.html
Puce
- 36,099
- 12
- 75
- 145
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
- 903
- 1
- 7
- 11