首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> Delphi

Delphi 統計中英文字元個數:區分雙位元組中文字與單位元組英數字元

     編輯:Delphi

問題分析

Windows 內部以 ANSI 編碼(雙位元組字元集 DBCS)處理中文,一個中文字佔 2 個位元組,英文數字佔 1 個位元組。若直接用 Length(String) 取得的是位元組數而非字元數。需逐字元檢查 ASCII 碼區分:

  • ASCII 33~126:可見英數符號(單位元組)
  • ASCII ≥ 127:中文字首位元組(雙位元組字元的第一個位元組)

統計函數

procedure CountChineseEnglish(const Text: string; out ChineseChars, EnglishChars: Integer);
var
  i: Integer;
  B: Byte;
begin
  ChineseChars := 0;
  EnglishChars := 0;
  i := 1;
  while i <= Length(Text) do
  begin
    B := Byte(Text[i]);
    if (B >= 33) and (B <= 126) then
    begin
      Inc(EnglishChars);
      Inc(i);
    end
    else if B >= 128 then
    begin
      Inc(ChineseChars);
      Inc(i, 2); // 跳過雙位元組第二個位元組
    end
    else
      Inc(i); // 控制字元等略過
  end;
end;

表單按鈕事件範例

procedure TForm1.Button1Click(Sender: TObject);
var
  Cn, En: Integer;
begin
  CountChineseEnglish(Memo1.Text, Cn, En);
  Label1.Caption := Format('英文字數:%d', [En]);
  Label2.Caption := Format('中文字數:%d', [Cn]);
end;

改進建議

  • 若專案使用 Unicode 版 Delphi (D2009+),String 為 UnicodeString,每個字元固定 2 位元組,中英文皆為 1 Char,可直接用 Length 或 TCharacter 分類,上述 ANSI 邏輯不再適用。
  • ANSI 版本中,若字串包含全形英文/數字(位元組值 ≥ 128),會被誤判為中文;實務上可結合 IsDBCSLeadByte API 更精確判斷。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved