I hope this doesn't already exist…
I got tired of building strings with &'s, so I wrote a Sub similar to C's sprintf function. It is very simple and handles only the %s, %d, and %f format types.
%d can have a field width specifying leading spaces or leading 0's to fill out the field width. For example, %5d will specify a field width of five with leading spaces, %05d will specify a field width of five with leading zeros.
%f can optionally specify field width, as in %5f. It can also specify field width and precision, as in %5.2f.
Below is the sprintf function code. I have also attached a little test project. If you find and fix errors, please share.
I got tired of building strings with &'s, so I wrote a Sub similar to C's sprintf function. It is very simple and handles only the %s, %d, and %f format types.
%d can have a field width specifying leading spaces or leading 0's to fill out the field width. For example, %5d will specify a field width of five with leading spaces, %05d will specify a field width of five with leading zeros.
%f can optionally specify field width, as in %5f. It can also specify field width and precision, as in %5.2f.
Below is the sprintf function code. I have also attached a little test project. If you find and fix errors, please share.
B4X:
Sub Sprintf(fmt As String, arg() As Object) As String
Dim ai, fi, i, j As Int
Dim exp, wid As Int
Dim stmp, ptmp, sres, c, s, t As String
Dim bdone As Boolean
ai = 0
fi = 0
stmp = ""
sres = ""
Do While (fi < fmt.Length)
c = fmt.CharAt(fi)
fi = fi + 1
If (c = "%") Then
stmp = ""
ptmp = ""
bdone = False
Do While ((fi < fmt.Length) AND (bdone = False))
c = fmt.CharAt(fi)
fi = fi + 1
If ((IsNumber(c) = True) OR (c = ".")) Then
ptmp = ptmp & c
bdone = False
Else If (c = "s") Then
stmp = arg(ai)
ai = ai + 1
sres = sres & stmp
bdone = True
Else If (c = "d") Then
If (ptmp.Length > 0) Then
t = " "
If (ptmp.CharAt(0) = "0") Then
t = "0"
ptmp = ptmp.SubString(1)
End If
End If
If (ptmp.Length > 0) Then wid = ptmp Else wid = 0
stmp = arg(ai)
Do While (stmp.Length < wid)
stmp = t & stmp
Loop
ai = ai + 1
sres = sres & stmp
bdone = True
Else If (c = "f") Then
If (ptmp.Length > 0) Then
i = ptmp.IndexOf(".")
If (i >= 0) Then
wid = ptmp.SubString2(0, i)
exp = ptmp.SubString(i+1)
Else
wid = ptmp
exp = 0
End If
stmp = NumberFormat(arg(ai), wid, exp)
Else
stmp = arg(ai)
End If
ai = ai + 1
sres = sres & stmp
bdone = True
Else
ai = ai + 1
End If
Loop
Else
sres = sres & c
End If
Loop
Return(sres)
End Sub