Android Code Snippet String Format

SubName: StringFormat (although it's an example and not a functioning sub)

Description: Format a string for output with spaces and number conversion using the static String function 'format' Documentation is here and the formatting string documentation is here. Although I've never used it, I've seen similar in other languages, so it may be familiar to you.

B4X:
    'Create a Stringbuilder (it's much faster for appending strings)
    Dim SB As StringBuilder
    SB.Initialize

    'Create the Formatter Object
    Dim Format As JavaObject
    Format.InitializeStatic("java.lang.String")

    'Create an array of arrays that holds our data.
    'We could have been read from a CSV file using StringUtils and converted to an array of arrays using Regex.Split

    'NOTE: the array must be of type Object

    Dim Data(4) As Object
    Data(0) = Array As Object("John","1","Home","\n")
    Data(1) = Array As Object("Peter","2","Home","\n")
    Data(2) = Array As Object("Michael","3","Away","\n")
    Data(3) = Array As Object("Ann","4","Home","\n")

    Dim FormatStr As String = "%-10s %3d %s%n"

    For Each Line() As Object In Data
        SB.Append(Format.RunMethod("format",Array As Object(FormatStr,Line)))
    Next

    Log(SB.ToString)

    'Could also add it to a Label or EditText that uses a Monospaced font.
    'Add it to our view
    'Views typeface must be mono spaced.
    'Label1.Typeface = Typeface.MONOSPACE
    'Label1.text = SB.ToString

Depends on: JavaObject

Tags: Format Output Strings
 
Last edited:
Top