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; 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.