B4J Code Snippet Java String formatter

Discussion in 'B4J Code Snippets' started by Daestrum, Jul 13, 2015.

Similar threads

B4A Tutorial [B4X] Smart String Literal
B4J Code Snippet [Class] Code Beautifier/Formatter
B4J Tutorial Designer Menu Items
B4J Library jTextFormatter
B4A Code Snippet [B4X] Bytes To File
  1. Daestrum

    Daestrum Well-Known Member Licensed User

    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
    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
    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