12-13-2024, 09:15 PM
I've found myself writing these functions:
Would it be of interest to incorporate MultiplyStr() and FormatStr() to ZXBasic?
I can prepare a PR if there is interest.
Code:
' Duplicates the string for times times.
' For instance, MultiPlyStr( "0", 3 ) ' -> "000"
' times must be between 1 and 127
function MultiplyStr(ByVal s as string, ByVal times as byte) as string
dim toret as string = ""
if times > 0
for i = 1 to times
toret = toret + s
next
end if
return toret
end function
' Returns a formatted string with the number n
' and enough preceding chars (the ch parameter),
' so that the length of the string is w or more.
' for instance, FormatStr(15, 4, "0") ' -> "0015"
' w must be between 1 and 127.
function FormatStr(ByVal n as integer, ByVal w as byte, ByVal ch as string) as string
dim toret as string = str( n )
dim len_prefix as byte = w - len( toret )
return MultiplyStr( ch( 0 ), len_prefix ) + toret
end function
sub testMultiplyStr()
print("'0' * -1: '" + MultiplyStr("0", -1) + "'")
print("'0' * 0: '" + MultiplyStr("0", 0) + "'")
print("'0' * 1: '" + MultiplyStr("0", 1) + "'")
print("'0' * 2: '" + MultiplyStr("0", 2) + "'")
print("'0' * 3: '" + MultiplyStr("0", 3) + "'")
print("'0' * 4: '" + MultiplyStr("0", 4) + "'")
print("'0' * 5: '" + MultiplyStr("0", 5) + "'")
end sub
sub testFormatStr()
print("fmt(1, '0', -1): '" + FormatStr(1, -1, "0") + "'")
print("fmt(1, '0', 0): '" + FormatStr(1, 0, "0") + "'")
print("fmt(1, '0', 1): '" + FormatStr(1, 1, "0") + "'")
print("fmt(1, '0', 2): '" + FormatStr(1, 2, "0") + "'")
print("fmt(1, '0', 3): '" + FormatStr(1, 3, "0") + "'")
end sub
I can prepare a PR if there is interest.
-- Baltasar