Development‎ > ‎VBScript‎ > ‎

String Formatting Class


'*********************************************************************************
'* Function signature:
'* Description:
'*                  
'*
'* Parameters
'*
'*
'*
'* Return Value
'*
'*********************************************************************************
Class StringClass
  Dim bNewLineExpression
  Dim bTabExpression
 
  Sub class_initialize
    bNewLineExpression = true
    bTabExpression = true 
  End Sub
 
  Function Format(sExpression, aParameters)
    Dim sResult
    Dim bGetID : cChar = false
    Dim cChar
    Dim iID
   
    Dim oFormatLookup : Set oFormatLookup = createobject("Scripting.Dictionary")
   
    for i = 1 to len(sExpression)
      cChar = Mid(sExpression, i, 1)         
     
      if cChar = "}" and bGetID then 'if the expression looks like }blah blah {0} the first braket will not cause error
        if not UBound(aParameters) < iID-1 and not oFormatLookup.Exists(iID) then
          oFormatLookup.Add "{" & iID & "}", aParameters(iID-1)
        end if
       
        bGetID = false
      end if
     
      if bGetID then
        iID = iID & cChar
      end if
     
      if cChar = "{" then
        bGetID = true
        iID = "" 'if the passed expression looks like {blah blah{0} the formatter will still work only for {0}
      end if     
    Next
   
    if bNewLineExpression then
       oFormatLookup.Add "\n", vbNewLine
    end if
   
    if bTabExpression then
       oFormatLookup.Add "\t", vbTab
    end if
   
    'Replace the {x} with the values
    sResult = sExpression
    for each key in oFormatLookup.Keys
      sResult = replace(sResult, key, oFormatLookup.Item(key))
    Next
   
    Format = sResult
  End Function
 
  Sub UnitTest
      MsgBox Format("Hello from {1}, Have a nice {2}", array("Joe", "Day"))
  End Sub
End Class


Dim oString : Set oString = new StringClass

'Code to unit test the class
oString.UnitTest

Comments