asp截取字符串长度问题

来源:百度知道 编辑:UC知道 时间:2024/05/22 10:54:01
我用asp想控制在数据库中读取字段串值的长度
如:name字段中有两个值
一个值:小老虎
别一个值:smalltiger
我想只读取前4个字节,也就是说结果是这样的:小老虎中只要 "小老"
而smalltiger中只要smal,这样的功能怎么实现啊。

我用了下面这个函数,但是当这个值是非字符会报错:
Microsoft VBScript 运行时错误 错误 '800a001c'

堆栈溢出: 'InterceptString'

<%
Function InterceptString(txt,length)
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 = InterceptString(trim(txt),ii) '字符串限长
exit for
end if
next
InterceptString = txt
else
InterceptString = ""
end if
End Function
%>
先谢谢你。
但是,我要的效果不是这样的。
这只是一个例子,因为name中的值是动态的。
也就没有办法用left了。你懂我的意思吗

应该是这样的:
response.write cutStr("小老虎",4)
response.write cutStr("smalltiger",4)
Function cutStr(str,strlen)
dim l,t,c
l=len(str)
t=0
for i=1 to l
c=Abs(Asc(Mid(str,i,1)))
if c>255 then
t=t+2
else
t=t+1
end if
if t>=strlen then
cutStr=left(str,i)
exit for
else
cutStr=str
end if
next
cutStr=replace(cutStr,chr(10),"")
end Function

Function 下面加一句On Error Resume Next

功能你都实现了,就是非字符时出错吧.那就让他非字符时不处理了吧.

response.write left("小老虎",2)
response.write left("smalltiger",4)