Did you ever need to quickly replace some placeholders in a string with a variable number of literals or variable values ?
Here’s a ssprintf() VB/A variant of C’s sprintf() function.
Let’s say that the first “s” in the name stands for “simplified”.
We’re – of course – far away from the full fledged power of the C function, but this may nonetheless come in handy or just be a starting point for your own custom implementation.
Check the comments for details.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
'Function ssprintf - Simplified sprintf 'In short, replaces placeholder tags in psModel with the values passed in the 'subsequent parameters. 'First tag is replaced by first parameter, etc. 'Placeholders are the numbers (from 1 up) of the subsequent parameters, 'surrounded by percent (%) signs. Can appear in any order. 'A doubled percent sign escapes a percent sign. 'Also replaces "\n" with vbCrLf and "\t" with vbTab. 'There's no other intelligence or similarities with the C functions, other than that. 'NOTE: don't put Chr$(1) in psModel, this will mess up the tag replacement sentinels. 'Example (type in immediate window): ' ?ssprintf("The quick brown %1% jumps over the lazy %2%", "fox", "dog") ' The quick brown fox jumps over the lazy dog' ' ?ssprintf("The quick brown %2% jumps over the lazy %1%", "fox", "dog") ' The quick brown dog jumps over the lazy fox Public Function ssprintf(ByRef psModel As String, ParamArray pavParams()) As String Dim sRet As String Dim iParams As Long Dim i As Long Const TAG_CRLF As String = "\n" Const TAG_TAB As String = "\t" On Error Resume Next iParams = UBound(pavParams) If iParams >= 0 Then sRet = Replace(psModel, "%%", Chr$(1)) For i = LBound(pavParams) To UBound(pavParams) sRet = Replace(sRet, "%" & i + 1& & "%", pavParams(i)) Next i sRet = Replace(sRet, Chr$(1), "%") End If If InStr(1, sRet, TAG_CRLF, vbBinaryCompare) Then sRet = Replace(psModel, "\\", Chr$(1)) 'escape backslash sRet = Replace(sRet, TAG_CRLF, vbCrLf, Compare:=vbTextCompare) sRet = Replace(sRet, Chr$(1), "\") End If If InStr(1, sRet, TAG_TAB, vbBinaryCompare) Then sRet = Replace(psModel, "\\", Chr$(1)) 'escape backslash sRet = Replace(sRet, TAG_TAB, vbTab, Compare:=vbTextCompare) sRet = Replace(sRet, Chr$(1), "\") End If ssprintf = sRet End Function |