日期:2014-05-17  浏览次数:20818 次

如何取得字符串的字节长度?
字符串中含单字节和双字节字符,如何取得其字节长度?

------解决方案--------------------
<script type= "text/javascript ">
var s= '中文,English ';
alert( "[ "+s+ "]的长度: "+s.replace(/[^\x00-\xff]/gi, 'xx ').length)
</script>
------解决方案--------------------
<script language= "javascript ">
function strlen(str)
...{ var len; var i; len = 0;
for (i=0;i <str.length;i++)
...{ if (str.charCodeAt(i)> 255) len+=2; else len++; }
alert( "长度为: "+len); }

strlen( "china中国 ");
</script>

在这个javascript脚本中,strlen函数逐个取str字符串中的Unicode字符,利用charCodeAt获取指定位置的字符的值(为数字形式,可和数字进行比较),因为英文字符的值总在0到255之间,所以我们可以认定,如果该值大于255,就表示是汉字,长度加2,否则长度加1,这样最终可得到这个字符串以字节计的长度,满足了我们的要求。

------解决方案--------------------
LenB(Str)
就可以了

<html>
<body>
<script language= "vbscript ">
Dim text
text = "字符串123 "
MsgBox Len(text)
MsgBox LenB(text)
</script>
</body>
</html>

单得到的是12,因为NT系统都同意用的UNICODE编码...用9X系统估计就能得到9了~
------解决方案--------------------
弱弱的问下楼主怎么调用你写的那个函数啊?
------解决方案--------------------
Function StrLength(txt) '计算字符串长度,英文字母为1,汉字为2
dim x,y,ii
txt=trim(txt)
x = len(txt)
y = 0
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
next
StrLength = y
End Function