VBScript 中的类似 printf() 的格式函数
一个 VBScript 中的格式函数,模拟 C 函数 printf()。
概述
函数 fmt
帮助你在 VBScript 中像在 C 语言中一样格式化字符串。
在 C 语言中,如果你写
printf( "this is %s number %d", "test", 1 );
那么在 VBScript 中,你将使用函数 fmt
像这样:
dim str
str = fmt( "this is %x number %x", Array("test", 1) )
详细说明
完整的函数如下所示:
' works like the printf-function in C.
' takes a string with format characters and an array
' to expand.
'
' the format characters are always "%x", independ of the
' type.
'
' usage example:
' dim str
' str = fmt( "hello, Mr. %x, today's date is %x.", Array("Miller",Date) )
' response.Write str
function fmt( str, args )
dim res ' the result string.
res = ""
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
if i<Len(str) then
' normal percent.
if Mid(str,i+1,1)="%" then
res = res & "%"
i = i + 1
' expand from array.
elseif Mid(str,i+1,1)="x" then
res = res & CStr(args(pos))
pos = pos+1
i = i + 1
end if
end if
' found a normal char.
else
res = res & Mid(str,i,1)
end if
next
fmt = res
end function
格式字符始终是 %x
,与实际类型无关,因为 VBScript 没有像整数或字符串这样的直接类型。
可以改进!
这个函数满足我在使用它的地方的需求,但可以通过一些方式扩展,使其行为更像 printf
。
- 可以扩展格式字符,例如,可以将
%x
分解为%d
用于整数,%x
用于十六进制数,%f
用于浮点数等。 - 还可以添加其他
printf
功能,例如前导零等等。
结语
一如既往:我编辑 VBScript 文件的技巧:尝试过很多编辑器(包括 Frontpage、InterDev 等),我发现最易于使用的程序是 EditPlus,你可以在 www.editplus.com 上找到它(我没有从他们那里得到报酬)。
如果您有任何问题,请随时通过电子邮件提问:keim@zeta-software.de。
历史
- 2000 年 1 月 20 日:初始发布