网络编程
位置:首页>> 网络编程>> Asp编程>> ASP截取中英文字符串固定长度

ASP截取中英文字符串固定长度

  发布时间:2009-08-19 17:12:00 

标签:asp,英文,字符串

纯粹的截取字符串其实比较简单,用一个Left就搞定,但一个是全英文标题,一个是全中文标题,或中文混合排在一起,长短不一就很明显了,要考虑到中文跟英文的区别.

  本代码截取长度的计算方式:一个汉字长度计算为1个,一个英文字母或数字或符号的长度计算为0.5个.所以一个汉字占两个英文字母或数字或符号.如 "截取字符串"的长度="abcdefghij"的长度. 代码比较简单,呵呵....希望适合你用....

GetString.asp
<%
Function GetStringLength(txt,length)
dim i
i=1
y=0
txt=trim(txt)
for i=1 to len(txt)
j=mid(txt,i,1)
if asc(j)>=0 and asc(j)《=127 then '汉字外的其他符号,如:!@#,数字,大小写英文字母
y=y+0.5
else '汉字
y=y+1
end if
if -int(-y) >= length then '截取长度
txt = left(txt,i)
exit for
end if
next
response.write txt
End Function
%>

调用方法:
<%call GetStringLength(txt,length)%>
说明:txt为需截取的字符串,length为截取长度,一个汉字的长度按1个计算,一个英文或数字符号的长度按0.5个计算

把英文字母,数字,符号,汉字分开计算的长度截取:
GetString2.asp
<%
Function GetStringLength(txt,length)
dim i
i=1
y=0
txt=trim(txt)
for i=1 to len(txt)
j=mid(txt,i,1)
if asc(j)>=0 and asc(j)《=32 then '控制字符或通讯专用字符
y=y
elseif asc(j)>=33 and asc(j)<=47 then '标点符号 ! " # $ % & ' ( ) * + , - . /
y=y+0.5
elseif asc(j)>=48 and asc(j)<=57 then '数字 0123456789
y=y+0.5
num=num+1
elseif asc(j)>=58 and asc(j)<=64 then '标点符号 : ; 《 = > ? @
y=y+0.5
elseif asc(j)>=65 and asc(j)<=90 then '大写英文字母 ABCDEFGHIJKLMNOPQRSTUVWXYZ
y=y+0.5
beng=beng+1
elseif asc(j)>=91 and asc(j)<=96 then '标点符号 [ \ ] ^ _ `
y=y+0.5
elseif asc(j)>=97 and asc(j)<=122 then '小写英文字母 abcdefghijklmcopqrstuvwxyz
y=y+0.5
seng=seng+1
elseif asc(j)>=123 and asc(j)<=126 then '标点符号 { } ~
y=y+0.5
else
y=y+1
chn=chn+1
end if
if -int(-y) >= length then
txt = left(txt,i)
exit for
end if
next
End Function
%>

调用方法同上.

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com