1. 程式人生 > >Delphi判斷字串中是否包含漢字,並返回漢字位置

Delphi判斷字串中是否包含漢字,並返回漢字位置

//1,函式程式碼

{

  判斷字串是否包含漢字
  // judgeStr:要判斷的字串
  //posInt:第一個漢字位置
}
function TForm2.IsHaveChinese(judgeStr: string; var posInt: integer): boolean;
var
  p: PWideChar; // 要判斷的字元
  count: integer; // 包含漢字位置
  isHave: boolean; // 是否包含漢字返回值
begin

  isHave := false; // 是否包含漢字返回值預設為false
  count := 1; // 包含漢字位置預設為1

  p := PWideChar(judgeStr); // 把要判斷字串轉換

  // 迴圈判斷每個字元
  while p^ <> #0 do
  begin
    case p^ of
      #$4E00 .. #$9FA5:
        begin
          isHave := true; // 設定是否包含漢字返回值為true
          posInt := count; // 設定包含漢字位置
          break; // 退出迴圈
        end;

    end;

    Inc(p);
    Inc(count); // 包含漢字位置遞增
  end;

  result := isHave;

end;

//2,例子:

procedure TForm2.Button3Click(Sender: TObject);
var
  testStr1, testStr2: string;
  posInt: integer;
begin
  testStr1 := '12345';
  testStr2 := '123漢字45';

  if self.IsHaveChinese(testStr1, posInt) = true then
  begin
    ShowMessage(testStr1 + ' 包含漢字 :' + inttostr(posInt));
  end
  else
  begin
    ShowMessage(testStr1 + ' 不包含漢字');
  end;

  if self.IsHaveChinese(testStr2, posInt) = true then
  begin
    ShowMessage(testStr2 + ' 包含漢字 :' + inttostr(posInt));
  end
  else
  begin
    ShowMessage(testStr2 + ' 不包含漢字');
  end;
end;