It's very slow compared to printF, though. Would love tips on improvement!
Code: Select all
EnableExplicit
Procedure.s formatString(string.s, *data_a = 0, *data_b = 0, *data_c = 0, *data_d = 0, *data_e = 0, *data_f = 0, *data_g = 0)
; format a string, like PrintF()
; this is slower than printf() in C
; in a for (x=0; x<20000; x++) the difference between the two is (on my system) around 40-50%...
Protected.s toInsert, _string = string, format
Protected.l cs, ci, cd, cf, tFormat, count, iteration, location
; get number of times we need to deal with this string
cs.l = CountString(string.s, "%s")
ci.l = CountString(string.s, "%i")
cd.l = CountString(string.s, "%d")
cf.l = CountString(string.s, "%f")
tFormat.l = cs.l + ci.l + cd.l + cf.l
; vvvv slower than above? vvvv
;tFormat.l = CountString(string.s, "%s") + CountString(string.s, "%i") + CountString(string.s, "%d") + CountString(string.s, "%f")
For count.l = 1 To tFormat.l
iteration.l = count.l - 1
location.l = FindString(_string.s, "%", 0) ;
format.s = Mid(_string.s, location, 2)
Select format.s
Case "%i"
Select iteration
Case 0 : toInsert = Str(PeekL(*data_a))
Case 1 : toInsert = Str(PeekL(*data_b))
Case 2 : toInsert = Str(PeekL(*data_c))
Case 3 : toInsert = Str(PeekL(*data_d))
Case 4 : toInsert = Str(PeekL(*data_e))
Case 5 : toInsert = Str(PeekL(*data_f))
Case 6 : toInsert = Str(PeekL(*data_g))
EndSelect
Case "%s"
Select iteration
Case 0 : toInsert = PeekS(*data_a)
Case 1 : toInsert = PeekS(*data_b)
Case 2 : toInsert = PeekS(*data_c)
Case 3 : toInsert = PeekS(*data_d)
Case 4 : toInsert = PeekS(*data_e)
Case 5 : toInsert = PeekS(*data_f)
Case 6 : toInsert = PeekS(*data_g)
EndSelect
Case "%d"
Select iteration
Case 0 : toInsert = Hex(*data_a)
Case 1 : toInsert = Hex(*data_b)
Case 2 : toInsert = Hex(*data_c)
Case 3 : toInsert = Hex(*data_d)
Case 4 : toInsert = Hex(*data_e)
Case 5 : toInsert = Hex(*data_f)
Case 6 : toInsert = Hex(*data_g)
EndSelect
Case "%f"
Select iteration
Case 0 : toInsert = StrF(PeekF(*data_a))
Case 1 : toInsert = StrF(PeekF(*data_b))
Case 2 : toInsert = StrF(PeekF(*data_c))
Case 3 : toInsert = StrF(PeekF(*data_d))
Case 4 : toInsert = StrF(PeekF(*data_e))
Case 5 : toInsert = StrF(PeekF(*data_f))
Case 6 : toInsert = StrF(PeekF(*data_g))
EndSelect
Default : toInsert = "[FORMAT_ERROR]"
EndSelect
_string.s = RemoveString(_string.s, format.s, #PB_String_CaseSensitive, location.l, 1)
_string.s = InsertString(_string.s, toInsert.s, location)
Next count.l
ProcedureReturn _string.s
EndProcedure
DisableExplicit
OpenConsole()
time.s = FormatDate("%mm/%dd/%yyyy", Date())
teeth.l = 5
PrintN(formatString("Today is: %s and I only have %i teeth left in my head!", @time, @teeth))
Print("Press any key to continue...")
While Not Inkey() : Delay(10) : Wend