ASP网站UTF8编码/GB2312编码中字符串截取函数和获取长度函数
成功志
ASP网站UTF8编码/GB2312编码中字符串截取函数和获取长度函数
2012-3-23 ok12

网站建设中,会遇到在GB2312下使用截取文字长度函数,转到UTF-8编码时,却不能正常进行取值,这是由于UFT-8编码在计算字符长度时不一样.


本文列举在GB2312编码及UFT-8编码中截取字符串函数:


UTF-8编码截取字符串函数:


 


********************************

'输入参数:

' 1、文字内容

' 2、文字最大长度

*********************************

Public Function CutStr1(Title,TLen)

Dim k,i,d,c

Dim iStr

Dim ForTotal


If CDbl(TLen) > 0 Then

k=0

d=StrLen(Title)

iStr=""

ForTotal = Len(Title)


For i=1 To ForTotal

c=Abs(AscW(Mid(Title,i,1)))

If c>255 Then

k=k+2

Else

k=k+1

End If


iStr=iStr&Mid(Title,i,1)


If CLng(k)>CLng(TLen) Then

iStr=iStr&".."

Exit For

End If

Next


CutStr1=iStr

Else

CutStr1=""

End If

End Function


 


GB2312编码截取字符串函数:


********************************

'输入参数:

' 1、文字内容

' 2、文字最大长度

*********************************


Function CutStr(Str,LenNum)

    Dim P_num

    Dim I,X

    If StrLen(Str)<=LenNum Then

        Cutstr=Str

    Else

        P_num=0

        X=0

        Do While Not P_num > LenNum-2

            X=X+1

            If Asc(Mid(Str,X,1))<0 Then

                P_num=Int(P_num) + 2

            Else

                P_num=Int(P_num) + 1

            End If

            Cutstr=Left(Trim(Str),X)&".."

        Loop

    End If

End Function


*************************************

'取字符串长度函数


*************************************


Function strLen(Str)

    If Trim(Str)="" Or IsNull(str) Then Exit Function

    Dim P_len,x

    P_len=0

    StrLen=0

    P_len=Len(Trim(Str))

    For x=1 To P_len

        If Asc(Mid(Str,x,1))<0 Then

            StrLen=Int(StrLen) + 2

        Else

            StrLen=Int(StrLen) + 1

        End If

    Next

End Function




从上述编码原理中得出的结论是:


  1.每个英文字母、数字所占的空间为1 Byte;

  2.泛欧语系、斯拉夫语字母占2 Bytes;

  3.汉字占3 Bytes。

  由此可见UTF8对英文来说是个非常诱人的方案,但对中文来说则不太合算,无论用ANSI还是 Unicode/UCS2来编码都只用2 Bytes,但用UTF8则需要3 Bytes。

  以下是一些统计资料,显示用UTF8来储存文件每个字符所需的平均字节:

  1.拉丁语系平均用1.1 Bytes;

  2.希腊文、俄文、阿拉伯文和希伯莱文平均用1.7 Bytes;

  3.其他大部份文字如中文、日文、韩文、Hindi(北印度语)用约3 Bytes;

  4.用超过4 Bytes的都是些非常少用的文字符号。


 

发表评论:
昵称

邮件地址 (选填)

个人主页 (选填)

内容