萬盛學電腦網

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

ASP 精準字數統計函數:中英文混排、空白符標準化處理

ASP 內建 Len 只能算字符數,無法區分中英文、處理多餘空白。本函數實現「中文算 2 字符、英文算 1、連續空白合併為一」的精準統計邏輯,適合標題截斷、內容摘要、字數限制場景。

完整函數代碼

<%
Function WordCount(strInput)
    Dim strTemp, i, charCode, charWidth, totalWidth
    
    If IsNull(strInput) Or strInput = "" Then
        WordCount = 0
        Exit Function
    End If
    
    ' 1. 標準化空白符:Tab、換行、回車 → 空格
    strTemp = Replace(strInput, vbTab, " ")
    strTemp = Replace(strTemp, vbCr, " ")
    strTemp = Replace(strTemp, vbLf, " ")
    
    ' 2. 去除首尾空格
    strTemp = Trim(strTemp)
    
    ' 3. 合併連續空格為單一空格
    Do While InStr(1, strTemp, "  ", 1) <> 0
        strTemp = Replace(strTemp, "  ", " ")
    Loop
    
    ' 4. 核心邏輯:逐字符判斷寬度
    totalWidth = 0
    For i = 1 To Len(strTemp)
        charCode = AscW(Mid(strTemp, i, 1))
        ' 中日韓統一表意文字範圍:視為雙字節 (寬度 2)
        If charCode > 255 Then
            totalWidth = totalWidth + 2
        Else
            totalWidth = totalWidth + 1
        End If
    Next
    
    ' 5. 返回字符寬度總和 (可按需除以 2 得「中文詞數」)
    WordCount = totalWidth
End Function
%>

使用範例

<%
Dim testStr : testStr = "Hello 世界  這是測試"  ' 含雙空格
Response.Write "原始長度:" & Len(testStr) & "<br>"        ' 18
Response.Write "字符寬度:" & WordCount(testStr) & "<br>"  ' 5*1 + 2*2 + 4*2 = 21
%>

邏輯說明

  1. 空白符標準化:統一將控制字符轉為空格,避免不可见字符干擾
  2. 連續空格合併:模擬瀏覽器渲染行為 (HTML 多空格合併為一)
  3. 寬度計算:AscW > 255 判定為雙字節字符 (中文、日文、韓文、全形符號)
  4. 返回值:總字符寬度。若需「中文詞數」,可 WordCount \ 2

進階擴展:按寬度截取字符串

Function LeftByWidth(str, targetWidth)
    Dim i, charCode, currentWidth, result
    currentWidth = 0
    result = ""
    For i = 1 To Len(str)
        charCode = AscW(Mid(str, i, 1))
        If charCode > 255 Then currentWidth = currentWidth + 2 Else currentWidth = currentWidth + 1
        If currentWidth > targetWidth Then Exit For
        result = result & Mid(str, i, 1)
    Next
    LeftByWidth = result
End Function

這對函數組合可完美解決「標題顯示兩行、超出顯示省略號」等排版難題。

copyright © 萬盛學電腦網 all rights reserved