Windows 內部以 ANSI 編碼(雙位元組字元集 DBCS)處理中文,一個中文字佔 2 個位元組,英文數字佔 1 個位元組。若直接用 Length(String) 取得的是位元組數而非字元數。需逐字元檢查 ASCII 碼區分:
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;
String 為 UnicodeString,每個字元固定 2 位元組,中英文皆為 1 Char,可直接用 Length 或 TCharacter 分類,上述 ANSI 邏輯不再適用。IsDBCSLeadByte API 更精確判斷。