看到有人问如何取中文为2的指定字符串字节数,研究一下:

80酷酷网    80kuku.com

  中文|字符串函数:strLeft(str,num)
用途:取指定字符串左边数num个字符,中文作为2个字符出现。
说明:如最后一个汉字取则多,不取则少,则不取,即实际取字符数为num-1个。
      如字符串第一个字符为中文,且num=1,则返回空字符串。
环境:在Win 2K Server + IIS5.0上运行通过,LANGUAGE=VBSCRIPT

'--------------------*****START*****--------------------

FUNCTION strLeft(str,num)

DIM p_str,p_num
    p_str = ""
    p_num = 0    '定义变量,标记中文为2字节时的实际字符数
    
IF TRIM(str)<>"" THEN

    FOR i = 1 TO num

        IF asc(mid(str,i,1))>255 OR ASC(mid(str,i,1))<0 THEN    '判断下一个欲取的字符所占字节数
            p_num = p_num + 2
        Else
            p_num = p_num + 1
        End IF

    IF p_num > num THEN EXIT FOR     
    
    NEXT
    
    p_str = Left(str,i-1)       '把i-1替换为i,则产生与“说明”中相反的情况。

END IF

strLeft=p_str

END FUNCTION

'--------------------******END******--------------------

实例:

<%
FUNCTION strLeft(str,num)

DIM p_str,p_num
    p_str = ""
    p_num = 0
    
IF TRIM(str)<>"" THEN

    FOR i = 1 TO num
    
        IF asc(mid(str,i,1))>255 OR ASC(mid(str,i,1))<0 THEN
            p_num = p_num + 2
        Else
            p_num = p_num + 1
        End IF
        
    IF p_num > num THEN EXIT FOR
    
    NEXT

    p_str = Left(str,i-1)
        
END IF

strLeft=p_str

END FUNCTION


aaa = "中华aaaaa人民共和国"

bbb=strLeft(aaa,n)
%>
<%=bbb%>

n值为3时,结果为"中";
n值为7时,结果为"中华aaa";
n值为11时,结果为"中华aaaaa人";
n值为14时,结果为"中华aaaaa人民".

分享到
  • 微信分享
  • 新浪微博
  • QQ好友
  • QQ空间
点击: