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 位元組數。