2017年6月21日 星期三

Delphi 判斷字串是否為中文字

可以透過 ByteType函式來判斷字串的內容,藉以辨識每個字節的型態。

function ByteType(const S: AnsiString; Index: Integer): TMbcsByteType;
function ByteType(const S: UnicodeString; Index: Integer): TMbcsByteType;

回傳內容:
mbSingleByte : 單字節字串
mbLeadByte   : 雙字節(中文字)字串的第一個字符
mbTrailByte  : 雙字節(中文字)字串的第二個字符

範例:
var
  Str, S1,S2 : String ;    // AnsiString
  I : integer ;
begin
  Str := '12判ew斷dd某一ccc個111' ;
  S1 := '' ;
  S2 := '' ;
  for I := 1 to Length(Str) do
  begin
    if ByteType(Str,I) = mbSingleByte then
      S1 := S1 + Str[I]
    else
    if ByteType(Str,I) in [mbLeadByte,mbTrailByte] then
      S2 := S2 + Str[I] ;

  end;
  // 輸出結果
  S1 -->  12ewddccc111
  S2 -->  判斷某一個
end ;

沒有留言:

張貼留言