[Gambas-user] How to generate a format string

T Lee Davidson t.lee.davidson at gmail.com
Thu Apr 6 20:33:04 CEST 2023


On 4/6/23 00:09, BB wrote:
> Hi folks,
> 
> I am looking for a good idea. How to assemble a formatting string from a reasonable sample of a string. For example, suppose I 
> have a string "13-Jul-23", I want to build "dd-mm-yy" as the result. Not limited to dates though, if the string is "$123.45" 
> then I need to recognise it as currency and generate that string accordingly. Has anyone done such a thing before?
> 
> tia
> 
> bruce

I have not done that before. The only idea I can come up with ATM is to use RegExp and loop through various potential patterns 
until a Match is found that indicates the type of string it is (ie. date, currency, etc). Then, Split the string into tokens and 
build the formatting string from their format. Analyzing a currency string might be relatively easy, so ...

[code]
Public Sub main()

   ' Let's assume we've already determined it's a date
   Dim sInput As String = "13-Jul-23"

   Dim sFormatChars As String[] = ["d", "m", "y"]
   Dim asTokens As String[]
   Dim sDateSeparator As String
   Dim iTokenLen As Integer
   Dim sFormatString As String = ""

   If InStr(sInput, "/") Then
     sDateSeparator = "/"
   Else If InStr(sInput, "-") Then
     sDateSeparator = "-"
   Endif
   asTokens = Split(sInput, sDateSeparator)
   For x As Integer = 0 To asTokens.Max
     iTokenLen = Len(asTokens[x])
     If iTokenLen > 3 Then iTokenLen = 4
     sFormatString &= String$(iTokenLen, sFormatChars[x]) & sDateSeparator
   Next
   sFormatString = Left(sFormatString, -1)

   Print sFormatString
End
[/code]


-- 
Lee



More information about the User mailing list