关注开源代码的实际应用
- Function StringFormat(sVal, aArgs)
- Dim i
- For i=0 To UBound(aArgs)
- sVal = Replace(sVal,"{" & CStr(i) & "}",aArgs(i))
- Next
- StringFormat = sVal
- End Function
使用方法:
- StringFormat("this {0} a tes{1} string containing {2} values", Array("is","t","some"))
http://www.codeproject.com/KB/vbscript/fmt.aspx
- '============================================================================
- ' takes a string with format characters and an array
- ' to expand.
- '
- ' the format characters are always "%x", independ of the
- ' type.
- '
- ' Use double percent (%%) to denote an actual percent
- '
- ' usage example:
- ' dim str
- ' str = fmt( "hello, Mr. %x, today's date is %x.", Array("Miller",Date) )
- ' response.Write str
- '
- ' additionally the support was added to allow for fixed field widths
- ' adding a number between the % and x will set the field width to at least that size
- ' example:
- ' str = fmt( "%10x %10x %10x", Array("Jason", "Steve", "Smith") )
- ' response.write str
- ' output:
- ' 'Jason Steve Smith '
- '============================================================================
- Function fmt(ByVal str, ByVal args)
- Dim res ' the result string.
- res = ""
- Dim oRE 'the RegEx
- oRE = New regexp
- Dim fieldLen ' length of the field
- Dim strOffset
- Dim argLen ' length of array string
- Dim strSearchOn ' string to perform RegEx on
- strSearchOn = ""
- Dim pos ' the current position in the args array.
- pos = 0
- Dim i
- For i = 1 To Len(str)
- ' found a fmt char.
- If Mid(str, i, 1) = "%" Then
- 'make sure we are not at the end of the string
- If i Then
- ' normal percent.
- If Mid(str, i + 1, 1) = "%" Then
- res = res & "%"
- i = i + 1
- Else
- ' determine if there is a field length
- oRE.Pattern = "%(\d*)x.*{Article.Explain}quot;
- oRE.Global = False
- oRE.IgnoreCase = False
- strSearchOn = Mid(str, i) ' the rest of the string
- fieldLen = oRE.Replace(strSearchOn, "$1")
- If fieldLen = "" Then
- ' no length specified, expand from array.
- res = res & CStr(args(pos))
- strOffset = 0
- Else
- ' field is specified, expand from array then pad
- res = res & CStr(args(pos))
- argLen = Len(CStr(args(pos))) ' this is how large the token was
- If argLen < fieldLen Then ' determine if we need more padding
- res = res & Space(fieldLen - argLen) ' add the padding to the string
- End If
- strOffset = Len(fieldLen)
- End If
- pos = pos + 1
- i = i + strOffset + 1
- End If
- End If
- ' found a normal char.
- Else
- res = res & Mid(str, i, 1)
- End If
- Next
- fmt = res
- ' clean-up
- oRE = Nothing
- End Function