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 Library jTextFormatter
B4A Code Snippet [B4X] Convert bitmap to BMP format
B4J Tutorial Designer Menu Items
  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
    Code:
    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
    Code:
    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
     
Loading...
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice