Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
String functions
#1
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.
-- Baltasar
Reply
#2
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?
---
Boriel
Reply
#3
> 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()?
-- Baltasar
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)