萬盛學電腦網

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

ASP 判斷中英混雜字串顯示長度(雙位元字元計為 2)

函數 StringLength

Function StringLength(Txt)
    Txt = Trim(Txt)
    Dim x, y, ii
    x = Len(Txt)
    y = 0
    For ii = 1 To x
        If Asc(Mid(Txt, ii, 1)) <= 2 Or Asc(Mid(Txt, ii, 1)) > 255 Then
            y = y + 2   ' 雙位元字元(中文、全形)
        Else
            y = y + 1   ' 單位元字元(英數、半形)
        End If
    Next
    StringLength = y
End Function

原理

逐字元檢查 Asc 值:ASCII 0~127 為單位元,128~255 視系統代碼頁可能為雙位元首位,>255 則為 Unicode 寬字元。此邏輯在傳統中文系統 (CP950/CP936) 下常用。

使用範例

<%
Response.Write StringLength("ABC") & "
" ' 3 Response.Write StringLength("中文") & "
" ' 4 Response.Write StringLength("AB中") & "
" ' 4 %>

現代替代

ASP.NET 可用 StringInfo.LengthInTextElements 或 Encoding.GetByteCount;前端 JS 可用 [...str].length 取得字元數(Unicode 碼位),或 new TextEncoder().encode(str).length 取得 UTF-8 位元組數。

copyright © 萬盛學電腦網 all rights reserved