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