萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP 程式設計

ASP 中英混雜字串長度檢測函數 StrLength

函數程式碼

Function StrLength(str)
    On Error Resume Next
    Dim WINNT_CHINESE
    WINNT_CHINESE = (Len("論壇") = 2)  ' 判斷系統是否雙位元環境
    
    If WINNT_CHINESE Then
        Dim l, t, c, i
        l = Len(str)
        t = l
        For i = 1 To l
            c = Asc(Mid(str, i, 1))
            If c < 0 Then c = c + 65536
            If c > 255 Then t = t + 1
        Next
        StrLength = t
    Else
        StrLength = Len(str)
    End If
    
    If Err.Number <> 0 Then Err.Clear
End Function

原理說明

  • WINNT_CHINESE 利用已知中文字「論壇」在雙位元系統下 Len 回傳 2(每字 2 Byte)來偵測環境。
  • 逐字元取 Asc:Asc 回傳 -32768~32767,負數轉正數加 65536。
  • Asc > 255 視為雙位元字元(中文/全形),顯示寬度 +1(總寬度 = 字元數 + 中文字數)。

使用範例

<%
Response.Write StrLength("Hello") & "
" ' 5 Response.Write StrLength("你好") & "
" ' 4 Response.Write StrLength("Hi你好") & "
" ' 6 %>

現代替代

ASP.NET: System.Globalization.StringInfo.GetTextElementEnumerator 或 Encoding.GetByteCount;JavaScript: [...str].length (碼位數) 或 new TextEncoder().encode(str).length (UTF-8 位元組數)。

copyright © 萬盛學電腦網 all rights reserved