B4J Code Snippet Java String formatter

I still think in Java terms when formatting strings, so I wrote this small snippet that allows me to do just that with strings.

These 3 routines do the work
B4X:
Sub inline As JavaObject
    Return Me
End Sub
Sub format(f As String,a() As Object) As String
    Return     inline.RunMethod("format",Array(f,a))
End Sub 
#if java
import java.lang.String;

static public String format(String f,Object... args){
    return String.format(f,args);
}
#end if

And I use them like this
B4X:
    Log(format("%.4s -- %.4s",Array("Fred","Bloggs")))             ' limit string length to 4 (Bloggs is truncated to Blog)
    Log(format("%2$s,%1$s was here!!",Array("Fred","Bloggs")))    ' reverse the args ( 2$ = arg#2, 1$ = arg#1 )
    Log(format("local time : %tT",Array(DateTime.Now)))            ' time format
    Log(format("4 digit number : %04d",Array(21)))                ' number with leading zeroes
    Dim xx As String
    xx = format("hex : %1$04x (%1$d)",Array(0x894))                'number in hex and also show decimal value
    Log(xx)                                                        ' refers to arg#1 twice
 
Top