萬盛學電腦網

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

ASP 中文長度計算與截取函數:StrLength、StrLeft、StrRight 支援雙位元組字元

ASP 正確處理中英混合字串長度與截取:StrLength/StrLeft/StrRight

VBScript 內建 Len/Left/Right 以 **位元組** 計算,中文字佔 2 位元組導致視覺長度錯誤。本文提供三個函數,依據 Asc 判斷字元是否為雙位元組 (中文/全形),以「字元寬度」計算長度與截取,完美替代內建函數。

StrLength:計算視覺字元寬度 (中文=2, 英文=1)

Function StrLength(Str)
    Dim Temp_Str, I, Test_Str
    Temp_Str = Len(Str)
    StrLength = 0
    For I = 1 To Temp_Str
        Test_Str = Mid(Str, I, 1)
        If Asc(Test_Str) > 0 Then
            StrLength = StrLength + 1   ' ASCII (0-127) 視為 1
        Else
            StrLength = StrLength + 2   ' 雙位元組字元視為 2
        End If
    Next
End Function

StrLeft:依視覺寬度從左截取指定長度

Function StrLeft(Str, L)
    Dim Temp_Str, I, Test_Str, lens
    Temp_Str = Len(Str)
    StrLeft = ""
    lens = 0
    For I = 1 To Temp_Str
        Test_Str = Mid(Str, I, 1)
        StrLeft = StrLeft & Test_Str
        If Asc(Test_Str) > 0 Then lens = lens + 1 Else lens = lens + 2
        If lens >= L Then Exit For
    Next
End Function

StrRight:依視覺寬度從右截取指定長度

Function StrRight(Str, L)
    Dim Temp_Str, I, Test_Str, lens
    Temp_Str = Len(Str)
    StrRight = ""
    lens = 0
    For I = Temp_Str To 1 Step -1
        Test_Str = Mid(Str, I, 1)
        StrRight = Test_Str & StrRight
        If Asc(Test_Str) > 0 Then lens = lens + 1 Else lens = lens + 2
        If lens >= L Then Exit For
    Next
End Function

使用範例

Dim s
s = "ABC中文123"
Response.Write "Len=" & Len(s) & " StrLen=" & StrLength(s) & "
" ' Len=10 StrLen=13 (3中文*2 + 7英文*1) Response.Write StrLeft(s, 8) & "
" ' ABC中文1 (寬度 3+2*2+1=8) Response.Write StrRight(s, 8) & "
" ' 中文123 (寬度 2*2+3=7? 實際從右算)

重要變數衝突警告

函數內使用變數 I 作為迴圈計數器,**若呼叫端也在使用 I 當迴圈變數**,會導致外層迴圈異常。建議:

  • 函數內改用 iLoop、idx 等獨特名稱。
  • 或呼叫端避免使用 I。

現代化替代方案

若環境支援 VBScript.RegExp,可用正則 (?:[^\x00-\x7F]|[\x00-\x7F]){n} 截取,或升級 ASP.NET 使用 StringInfo 類別正確處理 Unicode 字素叢集 (Grapheme Clusters)。

copyright © 萬盛學電腦網 all rights reserved