Delphi中實現全形轉半形
來源:互聯網
上載者:User
function SbctoDbc(s:string):string;
var
nlength,i:integer;
str,ctmp,c1,c2:string;
{
在windows中,中文和全形字元都佔兩個位元組,
並且使用了ascii chart 2 (codes 128 - 255 )。
全形字元的第一個位元組總是被置為163,
而第二個位元組則是相同半形字元碼加上128(不包括空格)。
如半形a為65,則全形a則是163(第一個位元組)、 193 (第二個位元組, 128 + 65 )。
而對於中文來講,它的第一個位元組被置為大於163,(
如 ' 阿 ' 為: 176 162 ),我們可以在檢測到中文時不進行轉換。
}
begin
nlength: = length(s);
if (nlength = 0 ) then
exit;
str: = '' ;
setlength(ctmp,nlength + 1 );
ctmp: = s;
i: = 1 ;
while (i <= nlength) do
begin
c1: = ctmp[i];
c2: = ctmp[i + 1 ];
if (c1 = # 163 ) then // 如果是全形字元
begin
str: = str + chr(ord(c2[ 1 ]) - 128 );
inc(i, 2 );
continue ;
end;
if (c1 > # 163 ) then // 如果是漢字
begin
str: = str + c1;
str: = str + c2;
inc(i, 2 );
continue ;
end;
if (c1 = # 161 ) and (c2 = # 161 ) then // 如果是全形空格
begin
str: = str + ' ' ;
inc(i, 2 );
continue ;
end;
str: = str + c1;
inc(i);
end;
result: = str;
end;