Forum
String functions - Printable Version

+- Forum (https://www.boriel.com/forum)
+-- Forum: Compilers and Computer Languages (https://www.boriel.com/forum/forumdisplay.php?fid=12)
+--- Forum: ZX Basic Compiler (https://www.boriel.com/forum/forumdisplay.php?fid=11)
+---- Forum: Wishlist (https://www.boriel.com/forum/forumdisplay.php?fid=14)
+---- Thread: String functions (/showthread.php?tid=2581)



String functions - baltasarq - 12-13-2024

I've found myself writing these functions:
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
Would it be of interest to incorporate MultiplyStr() and FormatStr() to ZXBasic?
I can prepare a PR if there is interest.


RE: String functions - boriel - 12-14-2024

Indeed I was thinking to incorporate this as a basic operation ala Python:

"string" * 5 produces "stringstringstringstringstring"

But I´d like to consult this with the community.
What do you think?


RE: String functions - baltasarq - 12-14-2024

> Indeed I was thinking to incorporate this as a basic operation ala Python:
> "string" * 5 produces "stringstringstringstringstring"

Well, that'd be ideal. I mean, at least for Multiplystr(). What do you think of FormatStr()?