sprintf() in java

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • santanuguchhait
    New Member
    • Nov 2008
    • 2

    sprintf() in java

    Hi,
    I want to get the sprintf() function in java.
    Please write the code of the following sprintf() function in java.

    sprintf(buff,"% 2.2X ",RValue);

    Here buff is a string variable and RValue is also a string variable. The middle parameter is the format. My question is how to store the value of RValue in buff using the format specified("%2.2 X ").
  • chaarmann
    Recognized Expert Contributor
    • Nov 2007
    • 785

    #2
    Strings are immutable in Java. So you have to use StringBuffer or StringBuilder for the "buff" result. (Another way would be to use it with different syntax:
    String buff=sprintf(fo rmat, RValue);)
    Java has PrintStream.pri ntf() method that works similar. Now you have to redirect the output of the PrintStream into a StringBuilder.

    Another alternative is the MessageFormat.f ormat() method.

    If you google then you can see that there are also a lot free libraries that contain a sprintf-like function for java. You can download the source code for them (or decompile) and see how they did it.

    Oh, i forgot: if you use the new Java 5 then you have a new method inside the String class:
    format(String format, Object ... args). You can use this as an sprintf equivalent.
    Also have a look at Formatter class.
    But if you must use an older version of Java, then only the MessageFormat.f ormat() and its derived classes can help you (or the direct work with StringBuffer).

    Comment

    Working...