一.目的
使用delphi进行区分一个字符串的汉字、英文字母且计算长度。
其中只用length无法区分中英文,因为汉字是占两个字符,而英文和数字只需要一个字符。
二.程序方法
1.最简便: length(字符串)
2.判断字符ASCII:知道完整的长度的同事,顺便统计出中英文字符的个数
3.判断字符字节: mbSingleByte:单字节; mbLeadByte:双字节前半; mbTrailByte:双字节后半;
procedure TForm1.btn1Click(Sender: TObject);
var
i,liEnglish,liChinese,liCht,liElse,l1,l2,size_1:integer;
s,getstr,sss,lll,ls:string;
begin
s :='今天是2024 年 4 月 3号 节假日假期要注意 安全!';
liEnglish:=0;
liChinese:=0;
liElse:=0;
l1 :=0;
l2 :=0;
for i:=1 to length(s) do
begin
if(ord(s[i])>=33)and(ord(s[i])<=126) then
begin
inc(liEnglish);
Label1.Caption:=inttostr(liEnglish); //数字、英文数
end
else
if (ord(s[i])>=127) then
begin
inc(liChinese);
liCht := (liChinese div 2); //汉字数
Label2.Caption:=inttostr(liChinese div 2); //汉字数
end
else
inc(liElse);
end;
size_1 :=1;
lll :=s;
for i:=1 to length(s) do
begin
sss:=s[size_1];
ls := '字符串:'+lll+',Begin:'+IntToStr(size_1);
if trim(lll)='' then
break;
lll:=copy(s,size_1,length(s)-size_1);
if SysUtils.ByteType(s,size_1) =mbSingleByte then
begin
l1 :=l1+1;
size_1 :=size_1+1;
//Inc(size_1);
end else
begin
if SysUtils.ByteType(s,size_1)=mbLeadByte then
begin
size_1 :=size_1+2;
l2 :=l2+1;
end
else
Inc(size_1);
end;
ls :=ls+',End:'+inttostr(size_1);
end;
Memo1.Clear;
Memo1.Lines.Add('字符串:'+s);
Memo1.Lines.Add('长度(Length):'+IntToStr(Length(s)));
getstr := '长度(字符法):'+IntToStr(liEnglish+liCht*2+liElse)+',中文:'+IntToStr(liChinese div 2)+'个,英文:'+IntToStr(liEnglish)+'个,其他'+IntToStr(liElse);
Memo1.Lines.Add(getstr);
Memo1.Lines.Add('长度(双字节法):英文'+IntToStr(l1)+',中文:'+IntToStr(l2)+',总计 = '+IntToStr(l1+L2*2));
end;