从网上找了一个可以根据字符串中所含中文英文的多少,自动截取字符串长度的函数。
代码如下:
Function
InterceptString(txt,length)
dim x,y,ii
txt = trim (txt)
x = len (txt)
y = 0
if x >= 1 then
for ii = 1 to x
if asc(mid(txt,ii,1)) < 0 or asc(mid(txt,ii,1)) >255 then
y = y + 2
else
y = y + 1
end if
if y >= length then
txt = left (txt,ii) ' 字符串限长
exit for
end if
next
if len (txt) < x then
InterceptString = txt & " .. "
else
InterceptString = txt
end if
else
InterceptString = ""
end if
End Function
dim x,y,ii
txt = trim (txt)
x = len (txt)
y = 0
if x >= 1 then
for ii = 1 to x
if asc(mid(txt,ii,1)) < 0 or asc(mid(txt,ii,1)) >255 then
y = y + 2
else
y = y + 1
end if
if y >= length then
txt = left (txt,ii) ' 字符串限长
exit for
end if
next
if len (txt) < x then
InterceptString = txt & " .. "
else
InterceptString = txt
end if
else
InterceptString = ""
end if
End Function
结果我在使用的时候,发现这个函数根本不能区别中文和英文。
经过一番查找,发现问题出在这一句:
if
asc
(
mid
(txt,ii,
1
))
<
0
or
asc
(
mid
(txt,ii,
1
))
>
255
then
因为我的网站使用的是utf-8编码,所以这句应该改为:
if
ascW(
mid
(txt,ii,
1
))
<
0
or
ascW(
mid
(txt,ii,
1
))
>
255
then
当然如果你用的是gb-2312编码就不需要修改了。
附:
AscW 是为使用 Unicode 字符的 32 位平台提供的。 它返回 Unicode (宽型)字符代码,因此可以避免从 ANSI 到 Unicode 的代码转换。